FFmpeg: How To loop an image and apply music to it (MP4)

At the end of this article -> Change the audio track in a video (ffmpeg)

you can find how to combine multiple audio tracks in a single file without loss of quality (usable when create music compilation).

Prepare music excerpt

To extract music excerpt from 01:07 with 04:09 duration use the following command. It is without loss of quality (just copying):

ffmpeg -ss 01:07 -i music.mp3 -t 04:09 -c copy excerpt.mp3

Encoding an image to x264 with music copying

Use the following command, specify own filenames and the second number in -framerate option (the video duration in seconds):

ffmpeg -framerate 1/249 -i scaled.jpg -i excerpt.mp3 -map 0:v -map 1:a \
-c:a copy -c:v libx264 -x264-params keyint=5:scenecut=0 -preset slow -r 1 -pix_fmt yuv420p result.mp4

-framerate 1/249 sets the video duration. “249” is a duration in seconds – 4 min 9 sec.

-map 0:v and -map 1:a sets the first file as our “video track” and the second one as “audio track”. It is important to use when a mp3 file contains an image as preview (for example the cover of a song).

-c:a copy and -c:v libx264 – copies the audio track and convert jpeg to x264

-x264-params keyint=5:scenecut=0 sets keyframe interval. Here “5” means 1 keyframe per 5 video frames. This optimizes the video and makes it easy to seek backward/forward. If this is not used, the media player may crash when you try to seek. Also without this option increases GPU/CPU usage when video playback.

Note more keyframes – larger filesize.

-preset slow – pretty fast encoding with good video compress and quality.

-r 1 – sets frames per second (fps) to “1”. With this we achieve fast encoding and less filesize. Since our video track is a single image this option is a good choice.

-pix_fmt yuv420p – not the best but supported everywhere pixel format (all browsers, media players).

Width or height not divisible by 2 (+ image scaling)

If you got the following message when encoding:

[libx264 @ 0x559d9111ad00] width not divisible by 2 (2201x2500)

Need to resize the image, ffmpeg can help in that case by using the following command:

ffmpeg -i image.jpg -compression_level 0 -vf scale=2200:-2 scaled.jpg

With -compression_level 0 option we don’t affect the image quality.

-vf scale=2200:-2 option sets the image width to “2200”, height value calculates itself based on the aspect ratio and “-2” calculates the nearest value dividable by 2.

The result

Now it is possible to play the video in media players and browsers:

mpv result.mp4
firefox result.mp4

Leave a Reply

Your email address will not be published.