Reputation: 10564
I have two files, in.mp4
and outro.mp4
.
I need a very simple thing: trim in.mp4
to an arbitrary lenght, and concat outro.mp4
after it.
I can do that without the trimming part
import ffmpeg
main_video = ffmpeg.input('in.mp4')
outro = ffmpeg.input('outro.mp4')
v1 = main_video.video.filter("scale", size='hd720')
a1 = main_video.audio
v2 = outro.video
a2 = outro.audio
joined = ffmpeg.concat(v1, a1, v2, a2, v=1, a=1).node
v3 = joined[0]
a3 = joined[1]
out = ffmpeg.output(v3, a3, 'out.mp4')
out.run()
But if I add the trimming here:
main_video = ffmpeg.input('in.mp4').trim(start_frame=0, end_frame=1000)
I get this error:
ValueError: Encountered trim(end_frame=1000, start_frame=0) <17c7b86357ec> with multiple outgoing edges with same upstream label None; a
split
filter is probably required
and if I try to do it here:
v1 = main_video.video.filter("scale", size='hd720').trim(start_frame=0, end_frame=1000)
a1 = main_video.audio.trim(start_frame=0, end_frame=1000)
I get these errors:
[Parsed_trim_2 @ 00000295587ca840] Media type mismatch between the 'Parsed_trim_2' filter output pad 0 (video) and the 'Parsed_concat_3' filter input pad 1 (audio)
[AVFilterGraph @ 00000295587cc800] Cannot create the link trim:0 -> concat:1
How can I solve this?
Upvotes: 2
Views: 5084
Reputation: 32094
You may use trim
filter for the video, atrim
filter for the audio, and cut both by duration:
import ffmpeg
#import subprocess
# Build synthetic video files (with audio):
##############################################################
# subprocess.run('ffmpeg -y -f lavfi -i testsrc=size=1280x720:rate=30 -f lavfi -i sine=frequency=500 -c:v libx264 -c:a ac3 -ar 22050 -t 100 in.mp4')
# subprocess.run('ffmpeg -y -f lavfi -i mandelbrot=size=1280x720:rate=30 -f lavfi -i sine=frequency=1000 -c:v libx264 -c:a ac3 -ar 22050 -t 10 outro.mp4')
##############################################################
main_video = ffmpeg.input('in.mp4')
outro = ffmpeg.input('outro.mp4')
# Assuming frame rate is 30 fps, 33.3 seconds applies 1000 frames.
v1 = main_video.video.filter('scale', size='hd720').filter('trim', duration=33.3) # Use trim filter for the video.
a1 = main_video.audio.filter('atrim', duration=33.3) # Use atrim filter for the audio.
v2 = outro.video
a2 = outro.audio
joined = ffmpeg.concat(v1, a1, v2, a2, v=1, a=1).node
v3 = joined[0]
a3 = joined[1]
out = ffmpeg.output(v3, a3, 'out.mp4')
out.run()
I tested the code above by generating synthetic video files (generated in the commented part).
Upvotes: 3