ffmpeg – How to merge MP4 video without audio with MP3 file using CLI tools, considering offset


Here’s how I’d suggest tackling this:

  1. First, create a silent video lasting 252 seconds.
  2. Then, re-encode your existing video file to match the format of the silent video.
  3. Merge the two videos to ensure the video file’s duration matches that of the audio file.
  4. Add the audio track onto the merged video file.

You’ll need ffmpeg, which you seem to already have, and mkvtoolnix, which can be installed with the following command:

sudo apt-get install mkvtoolnix

To create the silent video:

ffmpeg -f lavfi -i color=c=black:s=1280x720:r=30:d=252 -f lavfi -i anullsrc=r=44100:cl=stereo -c:v libx264 -t 252 -pix_fmt yuv420p -c:a aac -b:a 128k -strict experimental 'silent_video.mp4'

To re-encode the main video file in the same format as the silent video (it can take quite some time if you have a big video file):

ffmpeg -i 'only_video.mp4' -c:v libx264 -c:a aac -strict experimental -b:a 128k 'only_video_converted.mp4'

To merge the two silent video files into one (that’s why we needed to install mkvtoolnix: mkvmerge is a very easy to use video merge tool):

mkvmerge -o 'combined_video.mkv' 'silent_video.mp4' + 'only_video_converted.mp4'

To add the audio track onto the video file:

ffmpeg -i 'combined_video.mkv' -i 'only_audio.mp3' -c copy -map 0:v:0 -map 1:a:0 'final_video_with_audio.mkv'

Your video with synchronized audio and the first 252 seconds of audio only is ready!

In my test with a 33-second video and a 49-second audio segment, the results were as expected. However, be aware that processing times may significantly increase with the size of the video file.



Source link

Leave a Comment