Merging video and audio, with audio re-encoding

ffmpeg -i video.mp4 -i audio.wav -c:v copy -c:a aac output.mp4

Here, we assume that the video file does not contain any audio stream yet, and that you want to have the same output format (here, MP4) as the input format.

If your audio or video stream is longer, you can add the -shortest option so that ffmpeg will stop encoding once one file ends.

Copying the audio without re-encoding If your output container can handle (almost) any codec – like MKV – then you can simply copy both audio and video streams:

ffmpeg -i video.mp4 -i audio.wav -c copy output.mkv

Replacing audio stream If your input video already contains audio, and you want to replace it, you need to tell ffmpeg which audio stream to take:

ffmpeg -i video.mp4 -i audio.wav -c:v copy -c:a aac -map 0:v:0 -map 1:a:0 output.mp4

The -map option makes ffmpeg only use the first video stream from the first input and the first audio stream from the second input for the output file.

In case one would like to merge audio and video with different length and also to apply Fade In and Fade Out the following worked for me:

ffmpeg -i Video001.mp4 -i Audio001.mp3 -af afade=t=in:st=0:d=3,afade=t=out:st=47:d=4 -c:v copy -c:a aac -shortest Output.mp4

In my case above the video was of length 51 so I chose Fade In of length 3 [Sec] and Fade Out* of ~4 [Sec]. Since fading is applied by a filter it required transcoding of the audio. In the case above I chose aac encoding.

Here are additionals tips:

  • Trim Files ffmepg -i file.mkv -ss 00:27:53 -to 00:36:46 -c copy file-2.mkv
  • Downscale Videos ffmpeg -i file.mp4 -vf scale=640x480:flags=lanczos -c:v libx264 -preset slow -crf 21 output_compress_480.mp4

ffmpeg -i aliensound.m4a -ss 00:00:00 -to 00:00:08 -c copy t1.m4a