Converting audio to video using ffmpeg
Suppose that the audio file is input.mp3 and the target video file is output.mp4:
ffmpeg -i input.mp3 -f lavfi -i color=c=black:s=640x360:r=25 -shortest -c:v libx264 -preset veryslow -c:a copy -pix_fmt yuv420p output.mp4
-i input.mp3: Specifies the input audio file.
-f lavfi -i color=c=black:s=640x360:r=25: Generates a black video with a resolution of 640x360 (360p) and a frame rate of 25 fps.
-shortest: Ensures the output video ends when the audio ends.
-c:v libx264: Uses the H.264 codec for video encoding.
-preset veryslow: Sets the encoding speed/quality trade-off.
-c:a copy: This option tells ffmpeg to copy the audio stream directly without re-encoding.
-pix_fmt yuv420p: Ensures compatibility with most players.
Alternative params
To re-encode the audio
Change:
-c:a copy
To:
-c:a aac -b:a 192k
-c:a aac: Uses AAC codec for audio.
-b:a 192k (Optional): Sets the audio bitrate to 192 kbps. Not including this param will use the default bitrate for AAC.
Available presets
The -preset option allows you to choose a balance between encoding speed and compression efficiency when using the H.264 codec (libx264). Here are the commonly available presets:
- ultrafast: Very fast encoding, but large file sizes. Lowest compression efficiency.
- superfast: Faster than fast, with somewhat larger file sizes.
- fast: A good balance between speed and file size.
- medium: The default setting, providing a good balance of speed and compression.
- slow: Slower encoding, resulting in better compression and smaller file sizes.
- slower: Even slower, but achieves better quality per bitrate.
- veryslow: Very slow encoding with the best compression efficiency.
- placebo: Extremely slow, with negligible gains in quality. Not recommended for practical use.
Specify start and end time range
Suppose the desired time range is 0:10-0:30, add the following param after -i input.mp3 (or maybe position doesn’t matter?):
-ss 00:00:10 -to 00:00:30
-ss 00:00:10: Seeks to the start time (10 seconds) of the audio file.
-to 00:00:30: Specifies the end time (30 seconds) of the audio file.
Bulk convert
To convert ./*.mp3 to videos, use the following shell script:
for file in ./*.mp3; do
ffmpeg -i "$file" -f lavfi -i color=c=black:s=640x360:r=25 -shortest -c:v libx264 -preset veryslow -c:a copy -pix_fmt yuv420p "${file%.mp3}.mp4"
done
for file in ./*.mp3; do: Loops through each .mp3 file in the current directory.
"$file": Refers to the current file in the loop.
"${file%.mp3}.mp4": Changes the file extension from .mp3 to .mp4 while keeping the rest of the filename intact.
References
ChatGPT