FFmpeg: How To loop animation GIF and apply music to it (MP4)

In some cases, a GIF image is cooler than a static image when using with music. This note is about how to convert GIF to MP4 and loop it. Also will be mentioned the possibilities of a video resizing and audio applying.

What we have:

  • ffmpeg
  • GIF file which is named animation.gif
  • MP3 file which is named music.mp3

FPS value of our GIF file

We can find out fps value in order to use it when encoding MP4 video. Using the same fps rate will be faster for encoding, will save some memory and will not damage the video.

In the example below fps value is 12.5:

ffmpeg -hide_banner -i animation.gif
Stream #0:0: Video: gif, bgra, 1280x720, 12.50 fps, 12.50 tbr, 100 tbn, 100 tbc

Convert GIF to MP4 (x264, yuv420p, specify own fps value)

In the example below i used the simple options, yuv420p pixel format is supported in every browser and online service, so it is recommended for compatibility.

Pay attention to -r 12.5 option. This is our fps value from the GIF file, replace it with yours:

ffmpeg -i animation.gif -c:v libx264 -preset slow -r 12.5 -pix_fmt yuv420p animation.mp4

Scaling (1280×720 to 640×480 example)

This can be done by using -vf scale=width:height option (video filter).

But in the example below i have used width divided by DAR as a height parameter. By this method ffmpeg calculates the height based on our passed width. Thus, the video size will be 640×480:

ffmpeg -i animation.gif -c:v libx264 -vf scale=640:640/dar -preset slow -r 12.5 -pix_fmt yuv420p animation.mp4

Loop MP4 file as many times as we want

The first command (requires bash shell) creates a text file with 60 lines. Each line contains the filename (file ‘animation.mp4‘).

The second command reads these lines and sticks the video file together 60 times. This way the video will be repeated 60 times.

Make sure you are in the directory with your video file before executing the first command. I highlighted the parameters that you can change in the first command:

for i in {1..60}; do printf "file '%s'\n" animation.mp4 >> mylist.txt; done
ffmpeg -f concat -i mylist.txt -c copy loop.mp4

Copy MP3 file to MP4 container (there is no quality loss)

Now we have MP4 file looped. Time to apply some music. Here is the simplest example:

ffmpeg -i loop.mp4 -i music.mp3 -c copy -shortest clip.mp4

-shortest option stops the video encoding when one of the tracks is ends by duration (video or audio track).

Here is the example how to specify an audio fragment and apply it to the video:

ffmpeg -ss 02:36 -i music.mp3 -t 33 -c copy interval.mp3
ffmpeg -i loop.mp4 -i interval.mp3 -c copy -shortest clip.mp4

-ss option is specifying where is audio track starts.

-t option is specifying where is audio track ends.