Max Kaye's Site

Max's Microblog

Replies

TOC
ffmpeg script: mod-video-speed

this script will speed up (or slow down) video and audio via ffmpeg.

put the following in e.g., ~/.local/bin/mod-video-speed and chmod +x it.

#!/usr/bin/env python3

import subprocess
import sys, re

this_file = sys.argv[0]
filename = this_file.split('/')[-1]
args = sys.argv[1:]

if len(args) != 3:
  print(f'Error: need 3 args but you provided {len(args)}. {args}')
  print(f'\n\tUSAGE: {filename} INFILE OUTFILE SPEED')
  print(f'\n\tINFILE: input file (source)\n\tOUTFILE: output file (destination)')
  print(f'\tSPEED: the speed of the output video in the format `2x` or `1.43x` -- must end with `x`')
  sys.exit(1)

in_file = sys.argv[1]
out_file = sys.argv[2]
speed_raw = sys.argv[3]
speed_pattern = r'([0-9]+\.?[0-9]*)x'
speed_re = re.match(speed_pattern, speed_raw)
if speed_re is None:
  print(f"Error: SPEED argument did not match `{speed_pattern}`\n\nExamples: `1x`, `0.5x`, `123.456x`, `99x`")
  sys.exit(2)
speed = float(speed_re[1])
pts_speed = 1./speed
print(f"Processing {in_file} and modifying video speed to {speed}, outputting to {out_file}.")

ffmpeg_cmd_list = ['ffmpeg', '-i', in_file, '-filter_complex',
                   f"[0:v]setpts={pts_speed}*PTS[v];[0:a]atempo={speed}[a]",
                   '-map', '[v]', '-map', '[a]', out_file]
print(f"Running ffmpeg cmd: {' '.join(ffmpeg_cmd_list)}")
subprocess.run(ffmpeg_cmd_list)


license: public domain