FFmpeg Map Video from One File and Audio from Another
This guide provides a straightforward, step-by-step tutorial on how to combine a video track from one file and an audio track from a different file using the powerful command-line tool FFmpeg. You will learn the exact syntax required to map specific streams, how to copy the streams without losing quality, and how to handle potential issues like mismatched file lengths.
To map a video track from one file and an audio track from another,
you need to use FFmpeg’s -map option. This option allows
you to select specific streams from your input files and direct them to
the output file.
The Basic Command
The standard command to combine the first video stream of one file with the first audio stream of another file without re-encoding is:
ffmpeg -i video_source.mp4 -i audio_source.mp3 -map 0:v:0 -map 1:a:0 -c copy output.mp4How the Command Works
-i video_source.mp4: Defines the first input file (referred to as input0).-i audio_source.mp3: Defines the second input file (referred to as input1).-map 0:v:0: Tells FFmpeg to take input0(the video source), select the video stream type (v), and use the first video stream index (0).-map 1:a:0: Tells FFmpeg to take input1(the audio source), select the audio stream type (a), and use the first audio stream index (0).-c copy: Instructs FFmpeg to stream copy both the video and audio. This merges the files almost instantly without re-encoding, preserving the original quality of both tracks.output.mp4: The final merged file.
Re-encoding the Audio (If Needed)
If your audio source is in a format that is incompatible with your output container (for example, trying to put a high-quality WAV file into an MP4 container), you should re-encode the audio while keeping the video copy:
ffmpeg -i video_source.mp4 -i audio_source.wav -map 0:v:0 -map 1:a:0 -c:v copy -c:a aac output.mp4In this command, -c:v copy copies the video stream
without changes, while -c:a aac encodes the audio track
into the widely compatible AAC format.
Handling Different Stream Durations
If the video and audio tracks are of different lengths, the output
file will default to the duration of the longer file. If you want the
output file to stop as soon as the shortest track ends, add the
-shortest flag:
ffmpeg -i video_source.mp4 -i audio_source.mp3 -map 0:v:0 -map 1:a:0 -c copy -shortest output.mp4