Skip to content

Instantly share code, notes, and snippets.

@skarfie123
Created August 7, 2022 21:26
Show Gist options
  • Save skarfie123/e66a8fd55396dab6d2c012e05ad3d959 to your computer and use it in GitHub Desktop.
Save skarfie123/e66a8fd55396dab6d2c012e05ad3d959 to your computer and use it in GitHub Desktop.
extract segments from video clips and concatenate
import os
import subprocess
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
clip_times = {
"clip1.mp4": [
((2, 12), (2, 20)),
((2, 25), (2, 35)),
],
"clip2.mp4": [
((0, 2), (0, 15)),
((3, 25), (3, 35)),
((6, 20), (6, 35)),
((9, 0), (9, 15)),
((14, 10), (14, 15)),
((25, 8), (25, 15)),
((28, 38), (28, 48)),
((29, 35), (29, 42)),
],
}
def clip_name(clip, i):
return clip.replace(".", f"_{i}.")
def extract(clip, times):
for i, v in enumerate(times):
start_time = v[0][0] * 60 + v[0][1]
end_time = v[1][0] * 60 + v[1][1]
ffmpeg_extract_subclip(
clip, start_time, end_time, targetname=clip_name(clip, i)
)
def main():
for clip, times in clip_times.items():
extract(clip, times)
with open("clips.txt", "w", encoding="utf-8") as f:
for clip, times in clip_times.items():
for i in range(len(times)):
f.write(f"file {clip_name(clip, i)}\n")
subprocess.run(
[
"ffmpeg",
"-f",
"concat",
"-i",
"clips.txt",
"-c",
"copy",
"output.mp4",
],
check=True,
)
os.remove("clips.txt")
for clip, times in clip_times.items():
for i in range(len(times)):
os.remove(clip_name(clip, i))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment