Search code examples
audiovideoffmpeg

Why is adding background music to video using `ffmpeg -i input.mp4 -i music.mp3 output.mp4` not working?


I explored google and StackOverflow for how to add background music to the video and many of them suggested to use

ffmpeg -i input.mp4 -i audio.mp3 -shortest output.mp4

I have been trying to achieve this but it just does not work. When I try to add map like

ffmpeg -i "input.mp4" -i bg.mp3 -map 0:v:0 -map 1:a:0 oo.mp4

The video sound is replaced by the bg.mp3

And if I try -map 0 -map 1:a:0 or not provide map, the audio is not added at all.

How do I add the background music? I don't also get any error.


Solution

  • -map is a selector; select a type of stream from an input "file". To merge two audio streams, you need an audio filter:

    ffmpeg -i input.mp4 -i audio.mp3 -lavfi "[0:a][1:a]amerge[out]" -map 0:v -map [out]:a -shortest output.mp4
    
    • -lavfi: Same as -filter_complex, because you have two inputs
    • [0:a][1:a] take audio stream from the first and second inputs
    • -map 0:v select the video stream from the first input without processing
    • -map [out]:a select the audio stream from the filtergraph (processed)

    The shortest option in the amerge filter is set by default.

    If you have problems, you might want to check also the amix filter, the audio codecs of your files, and the volume filter to adjust the volume of the inputs in the filtergraph.

    Additional references: