FFmpeg实现多视频拼接加音频并匹配总时长的问题
Alright, let's sort out this FFmpeg one-liner problem you're facing. The issue here is that when you tried combining video concatenation and audio addition in a single command with -shortest, FFmpeg was using the shortest individual video's duration as the output length instead of the total concatenated video duration. That's because you weren't properly stitching the videos into a single continuous stream before merging with the audio.
Here's how to fix it with two reliable methods:
1. Using the Concat Filter (good for small number of videos)
If you don't want to rely on a vidlist.txt, use the concat filter to first stitch all your video streams into one, then merge with the audio. The -shortest flag will now truncate the audio to match the total concatenated video length:
ffmpeg -i video1.mp4 -i video2.mp4 -i your-audio-file.mp3 -filter_complex "[0:v][1:v]concat=n=2:v=1:a=0[v]" -map "[v]" -map 2:a -c:v libx264 -c:a aac -shortest output.mp4
- Adjust
n=2to match the number of videos you're concatenating. - Use
-c:v copyinstead of-c:v libx264only if all your input videos use the exact same video codec and parameters (this will speed up processing by avoiding re-encoding).
2. Using the Concat Demuxer (ideal for many videos with vidlist.txt)
If you're using a vidlist.txt to list your videos, first make sure your text file follows this format:
file 'path/to/video1.mp4' file 'path/to/video2.mp4' file 'path/to/video3.mp4'
Then run this single command—this method first concatenates all videos into a single stream via the demuxer, then merges with the audio, using -shortest to trim the audio to the total video duration:
ffmpeg -f concat -safe 0 -i vidlist.txt -i your-audio-file.mp3 -c:v copy -c:a aac -shortest output.mp4
-safe 0allows FFmpeg to read files using absolute paths (remove this if you're using relative paths that don't cross filesystem boundaries).- Again, replace
-c:v copywith-c:v libx264if your input videos have mismatched codecs.
Why your original single command didn't work
When you tried combining multiple video inputs directly with the audio without first concatenating them into a single stream, FFmpeg treated each video as a separate input. The -shortest flag then defaults to using the shortest duration among all individual inputs (your shortest video) instead of the total length of the stitched videos. By first creating a single concatenated video stream, you give FFmpeg a clear reference duration to match the audio against.
内容的提问来源于stack exchange,提问作者Rune Aspvik

