ffmpeg add audio but keep video length the same (not -shortest)
I'm adding audio to a video file using ffmpeg like so
ffmpeg -i videofile.mp4 -i audiofile.wav output.mp4
However this extends the output video file to be the length of the audio file if it is longer than the video. Using -shortest cuts the video file short if the audio file is shorter than the video. So is there a flag to tell ffmpeg to cut the keep the length of the output video to the length of the input video?
Solution 1:
- If video length is shorter than audio length,
-shortest
is what you want. - If video length is longer than audio length, no flag at all will be what you want.
There is no flag to automate this decision.
EDIT
Inspired by @deadcode's answer, I need to make clear, that "no flag to automate" is of course not true, if you are willing to reencode: In this case go with apad
as suggested by @deadcode.
If however you want to avoid reencoding (i.e. -c:v copy
) the answer stands.
There is a workaround using the ffconcat
demuxer, but it needs a bit of work:
- create a file containing silence in exactly the same format as your audiofile ("silence.wav")
- create a concat file "audio.ffconcat" (with as many silence lines as you need to make sure your audio is long enough):
.
file 'audiofile.wav'
file 'silence.wav'
file 'silence.wav'
...
file 'silence.wav'
- run
ffmpeg -i videofile.mp4 -f concat -i audio.ffconcat -c:v copy output.mp4
This will synthesize the apad
filter without a filter graph, thus allowing a mux without reencoding.
Solution 2:
I believe you can achieve your desired aim by using the -filter_complex option and the apad filter option to pad out your audio with silence at the end if the video is longer. Your command would be:
ffmpeg -i videofile.mp4 -i audiofile.wav -filter_complex " [1:0] apad " -shortest output.mp4
This assumes the audio you want is in the first stream of audiofile.wav, the [A:B] syntax says to take the B'th stream from the A'th input (both starting with 0, so [1:0] is the 1st stream from the 2nd input, or audiofile.wav above).
Details at: https://www.ffmpeg.org/ffmpeg-filters.html#Examples-68
Solution 3:
If you know the length of your video-file, you can accomplish that by using
ffmpeg -i videofile.mp4 -i audiofile.wav -t 43 output.mp4
Where 43 is the length of your video-file in seconds.