Adding Audio to a Video with Ffmpeg

From a speed and flexibility standpoint, Ffmpeg is hands down the best tool for adding an audio track to your video.

There are a multitude of codecs and file formats to choose from, referenced with a single command.

On Linux and MacOS you may either type your filenames into the command line or drag and drop entire pathnames. The following examples assume all input and output files are in the same folder.

On Linux, navigate to your folder and right click_Open in Terminal. On Mac OS, open a Terminal window and navigate to your folder.

If you have spaces or special characters in your filenames, remember to enclose them in quotes.

Add audio to video and stop when the shorter of the two sources is over:
$ ffmpeg -i Audio_file.wav -i Video_file.mp4 -shortest AV_output.mp4

Here is an example where quotes are needed:

$ ffmpeg -i ‘Audio filename.wav’ -i “Video_Filename#1.mp4” AV_output.mp4
Add audio to video and stop when the longer of the two sources is over:
$ ffmpeg -i Audio_file.wav -i Video_file.mp4 AV_output.mp4

If the audio track is longer, the last video frame will be held as a still image. If the video track is longer, silence will be inserted until the end.

Add audio to video and loop the video to match audio length:
$ ffmpeg -stream_loop -1 -i Video_file.mp4 -i Audio_file.wav -shortest -map 0:v:0 -map 1:a:0 -y AV_output.mp4
Add audio to video and loop the audio to match video length:
$ ffmpeg -stream_loop -1 -i Audio_file.wav -i Video_file.mp4 -i -shortest -map 0:a:0 -map 1:v:0 -y AV_output.mp4

By default, the aac codec is used for an mp4 container. If another audio codec is desired, use the audio codec flag after the input filenames. For example:

$ ffmpeg -i Audio_file.wav -i Video_file.mp4 -shortest -c:a alac AV_output.mp4

The -c:a alac flag tells ffmpeg to use the Apple Lossless Audio Codec. If Mac compatibility is required, you will also want to specify the yuv420p pixel format. As follows:

$ ffmpeg -i Audio_file.wav -i Video_file.mp4 -shortest -c:a alac -vf format=yuv420p AV_output.mp4
For a complete list of codecs/encoders:
$ ffmpeg -codecs
$ ffmpeg -encoders
For a complete list of file formats (containers):
$ ffmpeg -formats

If you have ffplay installed, you can use it to loop playback:

$ ffplay -loop 0 AV_output.mp4

Spacebar to pause/resume playback, Close window or Esc to stop.

Here is the movie I created from images using Ffmpeg, combined with the audio track created with Audacity:

Questions? Comments? Concerns? Leave them in a comment and I’ll do my best to address them. 🙂

Advertisement

One thought on “Adding Audio to a Video with Ffmpeg

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s