Merge Audio and Video with FFmpeg on Linux

This article provides a straightforward, step-by-step guide on how to combine separate audio and video files into a single multimedia file using FFmpeg on Linux. You will learn the core command to merge these files without re-encoding, how to handle files of differing lengths, and how to replace an existing audio track.

The Basic Merge Command

If you have a video file and an audio file, and you want to join them together without losing quality, you can use the stream copy feature in FFmpeg. This process is incredibly fast because it muxes the streams together instead of re-encoding the media.

ffmpeg -i input_video.mp4 -i input_audio.mp3 -c:v copy -c:a copy output.mp4

Command Breakdown

Handling Different File Lengths

Sometimes your audio file might be longer than your video file, or vice versa. By default, FFmpeg will keep rendering until the longest file ends, which can result in a frozen video frame or trailing silence.

To force the output file to stop as soon as the shortest input file finishes, add the -shortest flag:

ffmpeg -i input_video.mp4 -i input_audio.mp3 -c:v copy -c:a copy -shortest output.mp4

Replacing an Existing Audio Track

If your original video file already contains an audio track and you want to completely replace it with a new one, you need to tell FFmpeg to ignore the original audio stream. This is achieved using the -map option.

ffmpeg -i input_video.mp4 -i new_audio.wav -map 0:v:0 -map 1:a:0 -c:v copy -c:a aac output.mp4

Map Flag Breakdown