Replace a video's audio with an external audio file
Replacing the audio track is common: clean up a noisy production audio with a studio re-recording, swap the original soundtrack for a localized version, or add a different music track. The video is preserved exactly; the new audio replaces the old.
The command
ffmpeg -i input.mp4 -i audio.mp3 -c:v copy -c:a aac -map 0:v:0 -map 1:a:0 output.mp4What it does
FFmpeg reads the video from the first input and the audio from the second. -map 0:v:0 takes the video stream from input 0; -map 1:a:0 takes the audio stream from input 1. -c:v copy preserves the video packets; -c:a aac re-encodes the new audio to AAC. The original audio from input 0 is dropped because nothing maps to it.
When to use it
For any time the source video's audio needs to be replaced. The classic use is fixing bad production audio without re-encoding the video, which is the expensive part. It is also the right tool for adding a different language track or replacing music.
Video and audio requirements
Any decodable video and any decodable audio. The video and audio can have different durations; FFmpeg uses -shortest to stop at the shorter of the two if you add it. The default behavior is to use the video's duration, which truncates the audio if it is longer.
Things to avoid
- Forgetting
-map. Without it, FFmpeg may pick streams you did not expect, or fail if the streams have mismatched parameters. The explicit-mapmakes the intent clear. - Forgetting
-shortestwhen the audio is longer than the video. The output gets padded with silence, or the extra audio is dropped at the muxer, depending on the container. Add-shortestto make the behavior explicit. - Replacing audio in a source that has multiple audio tracks. With
-map 0:v:0 -map 1:a:0, the second audio track from input 0 is dropped. To preserve it, add another-mapfor it. - Forgetting to handle audio sync. If the new audio does not start at the same time as the video, add
-itsoffseton the audio input to shift it.