Skip to content

Instantly share code, notes, and snippets.

@namoshizun
Created June 11, 2018 10:56
Show Gist options
  • Save namoshizun/75e1089f4d75edc5156e6a423c019bed to your computer and use it in GitHub Desktop.
Save namoshizun/75e1089f4d75edc5156e6a423c019bed to your computer and use it in GitHub Desktop.
[Python + FFMPEG] change video speed without affecting pitch and/or concatenate multiple clips
from vid_utils import Video, concatenate_videos
videos = [
Video(speed=1.0, path="C:/temp/my_video_1.mp4"),
Video(speed=2.0, path="C:/temp/my_video_2.mp4"),
Video(speed=0.5, path="C:/temp/my_video_3.mp4"),
]
concatenate_videos(videos=videos, output_file=f"C:/temp/output_video.mp4")
import subprocess
from typing import List
ffmpeg_exe = "C:/__YOUR__/__PATH__/__TO__/ffmpeg.exe"
COMMAND_BASE = [ffmpeg_exe]
COMMAND_BASE += ["-n" ] # disable file overwriting
class Video():
def __init__(self, path:str, speed:float=1.0):
self.path = path
self.speed = speed
def concatenate_videos(videos:List[Video], output_file:str):
video_count = len(videos)
video_speeds = [float(1/x.speed) for x in videos]
audio_speeds = [float(x.speed ) for x in videos]
cmd_input_files = []
filters, concat = ("", "")
for i, x in enumerate(videos):
cmd_input_files += ["-i", x.path]
filters += f"[{i}:v] setpts = {video_speeds[i]} * PTS [v{i}];"
filters += f"[{i}:a] atempo = {audio_speeds[i]} [a{i}];"
concat += f"[v{i}][a{i}]"
concat += f"concat = n = {video_count}:v = 1:a = 1 [v_all][a_all]"
filter_complex = f"{filters}{concat}".replace(" ", "")
cmd_filter_complex = [
"-filter_complex", filter_complex,
]
cmd_map = [
"-map", "[v_all]",
"-map", "[a_all]",
]
command = sum([
COMMAND_BASE,
cmd_input_files,
cmd_filter_complex,
cmd_map,
[output_file],
], [])
subprocess.run(command)
@h8nor
Copy link

h8nor commented Oct 2, 2022

Excellent example changing speed of videos with subsequent concat. But is it possible to speed up the process?
Note: the key atempo can't be greater than 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment