Published on

Merge Audio and Video Files with FFmpeg

Authors
  • avatar
    Name
    Hieu Cao
    Twitter

Why Merge Audio and Video Files?

Merging audio and video files is essential for:

  • Creating Complete Media Files: Combine video streams with external audio tracks.
  • Replacing Audio Tracks: Add new soundtracks to existing videos.
  • Editing Projects: Finalize media files for playback or distribution.

What Does Merging Mean?

Merging refers to combining separate audio and video streams into a single file. FFmpeg enables this process seamlessly without re-encoding for fast and lossless results.


Merging Audio and Video Files

Basic Command

To merge an audio file with a video file:

ffmpeg -i video.mp4 -i audio.mp3 -c:v copy -c:a aac output.mp4
  • -i video.mp4: Input video file.
  • -i audio.mp3: Input audio file.
  • -c:v copy: Copy the video stream without re-encoding.
  • -c:a aac: Encode the audio using AAC.

Example: Merging a Background Track with a Video

ffmpeg -i myvideo.mp4 -i background_music.mp3 -c:v copy -c:a aac -b:a 192k final_output.mp4
  • -b:a 192k: Set the audio bitrate to 192 kbps for better quality.

Synchronizing Audio and Video

If the audio and video are out of sync, you can adjust the audio's start time:

ffmpeg -i video.mp4 -i audio.mp3 -c:v copy -c:a aac -b:a 192k -itsoffset 00:00:02 -map 0:v:0 -map 1:a:0 output.mp4
  • -itsoffset 00:00:02: Delay the audio by 2 seconds.
  • -map 0:v:0: Use the video stream from the first input.
  • -map 1:a:0: Use the audio stream from the second input.

Verifying the Merged File

Use FFprobe to check the streams in the output file:

ffprobe -i output.mp4

Look for both video and audio streams in the output.


Merging Multiple Files

To merge multiple audio and video files, use a text file to list inputs:

file 'video1.mp4'
file 'video2.mp4'
file 'video3.mp4'
file 'video4.mp4'

Then run:

ffmpeg -f concat -safe 0 -i file_list.txt -c copy output.mp4

Best Practices

  1. Ensure File Compatibility: Use formats and codecs that work well together.
  2. Sync Audio and Video: Adjust delays if necessary to prevent desynchronization.
  3. Use Copy Mode When Possible: Avoid re-encoding for faster merging and no quality loss.

Conclusion

Merging audio and video files with FFmpeg is a straightforward process, whether you're combining background music with a video or replacing an audio track. With powerful options and flexibility, FFmpeg makes it easy to create professional-quality media files. Start merging your audio and video today!