我需要裁剪视频文件的多个部分,并将其合并成一个新的视频。
如果我只想剪下一部分,我会做:
ffmpeg -i video.mp4 -ss 00:00:03.500 -to 00:00:08.500 -async 1 cut.mp4 -y
我想剪多个部分,然后合并所有的裁剪:
#视频裁剪:
ffmpeg -ss 00:00:09.846609 -to 00:00:12.263177 -i a.mp4 b.mp4
ffmpeg -ss 00:00:27.916761 -to 00:00:28.890601 -i a.mp4 c.mp4
#视频合并:
echo file 'b.mp4' >> concat.txt
echo file 'c.mp4' >> concat.txt
ffmpeg -f concat -i concat.txt end.mp4
但对于较大的视频文件,这是非常低效的。
为了进行两次切割,我使用过滤器复合体
如果我这样做,我会得到一个没有音频的视频:
command = 'ffmpeg -i video.mp4 \
-filter_complex "\
[0]trim=start_frame=10:end_frame=20[v0];\
[0]trim=start_frame=30:end_frame=40[v1];\
[v0][v1]concat=n=2[v5]"\
-map [v5] -async 1 output.mp4'
如果我这么做,事情就会一团糟:
ffmpeg -y -i video.mp4 \
-filter_complex "\
[0:v]trim=start_frame=10:end_frame=20[v0];\
[0:a]atrim=start=10:end=20[a0];\
[0:v]trim=start_frame=30:end_frame=40[v1];\
[0:a]atrim=start=30:end=40[a1];\
[v0][a0][v1][a1]concat=2:v=1:a=1[v5][a]"\
-map [v5] -map [a] -async 1 output.mp4
我甚至尝试用Python中的ffmpeg Python(GitHub - kkroening/ffmpeg-python: Python bindings for FFmpeg - with complex filtering support)来实现这一点,但也无法让音频工作。
最终通过选择过滤器实现了该需求:
ffmpeg -i video -vf "select='between(t,4,6.5)+between(t,17,26)+between(t,74,91)',setpts=N/FRAME_RATE/TB" -af "aselect='between(t,4,6.5)+between(t,17,26)+between(t,74,91)',asetpts=N/SR/TB" out.mp4
select及其对应的滤波器分别应用于视频和音频,选择的分段是4到6.5秒,17到26秒,最后是74到91秒;时间戳与设置点及其对应的过滤器保持连续。