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

  • -i input_video.mp4: Specifies the input video file.
  • -i input_audio.mp3: Specifies the input audio file.
  • -c:v copy: Copies the video stream directly without re-encoding.
  • -c:a copy: Copies the audio stream directly without re-encoding.
  • output.mp4: The name of the newly created file containing both streams.

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

  • -map 0:v:0: Takes the first video stream (v:0) from the first input file (0, which is input_video.mp4).
  • -map 1:a:0: Takes the first audio stream (a:0) from the second input file (1, which is new_audio.wav).
  • -c:a aac: Encodes the audio to AAC format, which is widely compatible with MP4 containers if your source audio is uncompressed (like a WAV file).