How to Add Audio to a Video With FFmpeg (Copy the Picture, Pin the Length, Prove It With pytest)
TL;DR: to add audio to a video with FFmpeg, copy the picture, take the sound from the second input, and pin the output to the video's own length: ffmpeg -i video.mp4 -i song.m4a \ -map 0:v:0 -map 1:a:0 -c:v copy \ -af "adelay=0:all=1,apad" -c:a aac -b:a 192k \ -t "$(ffprobe -v error -select_streams v:0 -show_entries stream=duration -of csv=p=0 video.mp4)" \ out.mp4 The rest of this post shows why…
<report>How to Add Audio to a Video With FFmpeg</report>
The article provides a step-by-step guide on how to add audio to a video using FFmpeg, a powerful command-line tool for multimedia processing. The key steps involve copying the video frame stream, taking the audio from a separate input file, and pinning the output length to the video's duration. The author demonstrates the process by providing a working FFmpeg command and then wraps it in a Python function that includes pytest checks to ensure the output is correct.
The video clip used for testing was sourced from an AI-generated video without an audio track, ensuring that the method works for videos with no original audio. The solution addresses common pitfalls, such as FFmpeg keeping the video running until the longest input stream ends or simply cutting the video to match the audio length, neither of which meet the requirement of aligning the audio's length to the video's duration.
Brief written by urgent.news from Dev.to's own syndicated text. Machine-written — may contain errors; check the original before relying on it.
This story
This is one outlet's version. Read the fullest account.