Skip to content

Instantly share code, notes, and snippets.

@ckhung
Created May 22, 2021 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckhung/6e9c6bf47a1f977f2f16da4707664361 to your computer and use it in GitHub Desktop.
Save ckhung/6e9c6bf47a1f977f2f16da4707664361 to your computer and use it in GitHub Desktop.
generate ffmpeg command to do xfade
#!/usr/bin/python3
# https://stackoverflow.com/a/66546687
# https://newtoypia.blogspot.com/2021/05/ffmpeg.html
# 一口氣串接爆多影片? ffmpeg 拯救可憐的手指
import argparse, subprocess, re
def gen_filter(segments, effect='fade', duration=0.3):
video_fades = ''
# fail! audio_fades = '\\\n[0:a]aresample=async=1;'
audio_fades = ''
settb = ''
last_fade_output = '0:v'
last_audio_output = '0:a'
video_length = 0
file_lengths = [0]*len(segments)
input_files = ''
for i in range(len(segments)):
settb += '\\\n[{:d}]settb=AVTB[{:d}:v];'.format(i,i)
input_files += ' -i ' + segments[i]
for i in range(len(segments)-1):
# file_lengths[i] = float(ffmpeg.probe(segments[i])['format']['duration'])
file_lengths[i] = float(
subprocess.check_output(
re.split('\s+', 'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1') + [segments[i]]
)
)
video_length += file_lengths[i]
next_fade_output = 'v{:d}{:d}'.format(i, i+1)
video_fades += '\\\n[{}][{:d}:v]xfade=transition={}:duration={:0.2f}:offset={:0.2f}'.format(
last_fade_output, i+1, effect, duration, video_length - duration*(i+1)
)
video_fades += '[{}];'.format(next_fade_output) \
if i < len(segments)-2 \
else ',format=yuv420p;'
last_fade_output = next_fade_output
next_audio_output = 'a{:d}{:d}'.format(i, i+1)
audio_fades += '\\\n[{}][{:d}:a]acrossfade=d={:0.2f}'.format(
last_audio_output, i+1, duration
)
if (i) < len(segments)-2:
audio_fades += '[{}];'.format(next_audio_output)
last_audio_output = next_audio_output
return 'ffmpeg {} -filter_complex "{}"'.format(
input_files, settb + video_fades + audio_fades
)
parser = argparse.ArgumentParser(
description='generate parameters for xfade of ffmpeg',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-o', '--outfile', type=str, default='out.mp4',
help='output file name')
parser.add_argument('-e', '--effect', type=str, default='fade',
help='transition effect')
parser.add_argument('-d', '--duration', type=float, default=0.3,
help='transition duration')
parser.add_argument('videofiles', nargs='*', help=u'v1.mp4 v2.mp4 ...')
args = parser.parse_args()
print(gen_filter(args.videofiles, effect=args.effect, duration=args.duration) + '\\\n ' + args.outfile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment