Configure FFmpeg apad Filter to Stop with Video
When padding audio in FFmpeg using the apad filter, the
output stream can run indefinitely because the filter pads the audio
with infinite silence by default. This article provides a direct,
step-by-step guide on how to configure FFmpeg so that the
apad filter stops processing automatically the moment your
video stream ends, preventing infinitely growing file sizes.
The Problem: Why apad Runs Forever
The apad (audio pad) filter is designed to add silence
to the end of an audio stream. If you apply apad without
any constraints, FFmpeg will continue generating silent audio frames
forever, even after the video stream has finished. To stop this, you
must instruct FFmpeg to terminate the output generation when the
shortest input stream (the video) ends.
The Solution: Using the
-shortest Flag
The most efficient way to stop the apad filter when the
video ends is to use the global -shortest option. This
tells FFmpeg to stop writing to the output file as soon as the shortest
stream (typically the video) finishes.
Here is the standard command structure:
ffmpeg -i input_video.mp4 -i input_audio.wav -filter_complex "[1:a]apad[padded_audio]" -map 0:v -map "[padded_audio]" -shortest output.mp4How This Command Works:
-i input_video.mp4: Defines the video source (Stream 0).-i input_audio.wav: Defines the audio source (Stream 1).-filter_complex "[1:a]apad[padded_audio]": Takes the audio from the second input (1:a), applies theapadfilter to add silence to the end, and labels the output stream as[padded_audio].-map 0:v: Maps the video from the first input to the final output.-map "[padded_audio]": Maps the padded audio stream to the final output.-shortest: This is the key parameter. It forces FFmpeg to stop encoding the moment the video stream (0:v) ends, cutting off the infinite silence generated byapad.
Alternative: Limit Padding by Sample Count
If you do not want to use the -shortest flag, you can
configure the apad filter to add a specific amount of
silence instead of an infinite amount. This is useful if you know the
exact duration differences beforehand.
whole_len: Specifies the target minimum length of the audio stream in samples.pad_len: Specifies the exact number of silent samples to append.
Example of adding exactly 44,100 samples of silence (1 second of silence at 44.1 kHz):
ffmpeg -i input_video.mp4 -i input_audio.wav -filter_complex "[1:a]apad=pad_len=44100[padded_audio]" -map 0:v -map "[padded_audio]" output.mp4