使用 FFMPEG 将修剪后的音频插入视频

Insert trimmed audio into a video with FFMPEG

最近我不得不使用 FFMPEG,有时我很难理解我应该使用哪个 commands/filters 来实现我的目标,这个 post 只是为了分享知识我在这个过程中获得了,特别是在处理音频文件并将其插入视频的过程中。

我需要用一个新的音频文件替换一个视频的音频,在特定的位置和特定的持续时间,最好在音频结束时淡出,下面是我的问题的解决方案及其解释。

我还应该提一下,获得了这部分所需的知识 通过研究rajib in this post提供的答案,非常感谢他!

这是完整的命令,提供了一个名为 vinput.mp4 的输入视频文件和一个名为 ainput.wav:

的音频文件
ffmpeg -y -i vinput.mp4 -i ainput.wav -filter_complex "\
 [1:a]aloop=-1:2e+09[aloop];\
 [aloop]aformat=channel_layouts=mono,atrim=end=2[atrim];\
 [atrim]adelay=2000[afinal];\
 [afinal]afade=t=out:st=3.5:d=0.5[afinal]" \
-shortest -map "[afinal]" -map 0:v output.mp4

下面是每一步的解释:

[1:a]aloop=-1:2e+09[aloop]

Will loop my audio an infinite number of times (-1), and repeat the maximum number of frames possible (2e+09) (I didn't find a way t tell the command to just repeat the audio in full...


[aloop]aformat=channel_layouts=mono,atrim=end=2[atrim]

This takes the looped audio from the previous instruction (aloop) and mainly trims it to last only 2 seconds.


[atrim]adelay=2000[afinal]

This will delay the start of the audio by 2000 miliseconds (2 seconds), making it start playing at the second second of the video.


[afinal]afade=t=out:st=3.5:d=0.5[afinal]

This will fade out our audio, starting the fade out on the 4th second of the video, and making the fadeout last for 0.5 seconds, meanind the sound will fade out from second 3.5 to 4.


-shortest

Since we have an audio stream that is being repeated indefinitely, we need to tell ffmpeg when to stop the encoding, this is done by the tag, which tells ffmpeg that we expect out final result to last as long as the shortest input it received (in out case, the video input).


-map "[afinal]" -map 0:v

As Samuel Williams kindly pointed out in , this option instructs ffmpeg what streams we want to copy to the output generated, in this case, we want to have both the final audio (afinal) and the source video stream (0:v).

-map 选项指示 ffmpeg 你想要什么流。要从 input_0.mp4 复制视频和从 input_1.mp4 复制音频:

$ ffmpeg -i input_0.mp4 -i input_1.mp4 -c copy -map 0:0 -map 1:1 -shortest out.mp4