Skip to content

Instantly share code, notes, and snippets.

@laygond
Last active June 24, 2020 22:42
Show Gist options
  • Save laygond/58ab352562fecb362d91edaf4437dd36 to your computer and use it in GitHub Desktop.
Save laygond/58ab352562fecb362d91edaf4437dd36 to your computer and use it in GitHub Desktop.
Trims a video from terminal given start and end time as well as input and ouput path. If time not specified it assumes beginning or end of video. If destination path not specified it uses same as input path.
# Trims a video given start and end time and input and ouput path
# (if time not specified it assumes beginning or end of video)
# (if destination path not specified it uses same as input path)
# by Bryan Laygond
# USAGE:
# python videotrim.py --input "Path/to/source/file" \
# --output "Path/to/destination/file" \
# --start 2.0 \
# --end 7.0
import os
import argparse
from moviepy.editor import VideoFileClip,VideoClip
# argument parser
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required = True,
help = "path to input video")
ap.add_argument("-o", "--output", type = str, default = "",
help = "path to output video")
ap.add_argument("-s", "--start", type = float, default = 0.0,
help = "trim start time in seconds")
ap.add_argument("-e", "--end", type = float, default = -1.0,
help = "trim end time in seconds")
args = vars(ap.parse_args())
# Create video object
clip = VideoFileClip(args["input"])
# Set parameters if not specified:
# for dest_path
if args["output"] == "":
input_path_part = args["input"].split(".") # sample & mp4 has been split
dest_path = input_path_part[0] + "_output." + input_path_part[1]
else:
dest_path = args["output"]
# for end_time
max_time = clip.duration
if args["end"] < 0 or args["end"] > max_time:
end_time = max_time
else:
end_time = args["end"]
# Trim and Write
trim_clip = clip.subclip(args["start"], end_time)
trim_clip.write_videofile( dest_path )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment