Monday, 8 November 2021

Convert an image and audio file to a video with ffmpeg

I needed a command line script to merge an image file with an audio file and generate a video file video.mp4 The first attempt was basic.
ffmpeg -loop 1 -i image.jpg -i audio.mp3 -c:a copy -c:v libx264 -shortest video.mp4
In most cases, this would do, but the image dimensions were not divisible by 2 resulting in an error.
[libx264 @ 0x56450842d500] height not divisible by 2 (640x427)
Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height
Conversion failed!
The current working version of the command line is as follows:
ffmpeg -loop 1 -i image.jpg -i audio.mp3 -vf "scale=2*trunc(iw/2):2*trunc(ih/2),setsar=1" -c:a copy -c:v libx264 -shortest video.mp4

Example: