Skip to content

Instantly share code, notes, and snippets.

@davidjmerritt
Last active July 21, 2017 17:07
Show Gist options
  • Save davidjmerritt/2c61b2097b1e27f3ea5dff26fe1d59ce to your computer and use it in GitHub Desktop.
Save davidjmerritt/2c61b2097b1e27f3ea5dff26fe1d59ce to your computer and use it in GitHub Desktop.
A base for programmatically clipping video using FFmpeg.
#!/usr/bin/python
import subprocess, time, os
def run_command(command):
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate()[0]
return output[:-1]
def create_clip(video_file, out_path, in_point, out_point, report_path=None, clip_type="encode"):
time_stamp = str(int(time.time()))
out_file = out_path+"/ffmpeg_clip_"+time_stamp+"_"+os.path.basename(video_file)
if report_path == None:
report_path = os.path.dirname(out_path)
report = report_path+"/ffmpeg_clip_"+time_stamp+"_"+os.path.splitext(os.path.basename(video_file))[0]+".txt"
if clip_type == "clip":
# This command is instant but video playback is off
command = 'ffmpeg -i '+video_file+' -ss '+in_point+' -to '+out_point+' -c copy '+out_file+' 2>>'+report
elif clip_type == "encode":
# This command requires a transcode ...
command = 'ffmpeg -i '+video_file+' -ss '+in_point+' -to '+out_point+' -c:v h264 -c:a aac '+out_file+' 2>>'+report
print command
run_command(command)
if __name__ == "__main__":
import sys
input_file_path = sys.argv[1] # ex. "/Path/to/input.mp4"
output_folder_path = sys.argv[2] # ex. "/Path/to/output/folder/for/video/"
in_point = sys.argv[3] # ex. "00:00:0.0"
out_point = sys.argv[4] # ex. "00:00:15.0"
create_clip(input_file_path, output_folder_path, in_point, out_point, clip_type="encode")
# Change "encode" to "clip" to run the faster version (no transcoding) but buggier
# EXAMPLE OF RUNNING
# python ffmpeg_clipping.py /Path/to/input.mp4 /Path/to/output/folder/for/video 00:00:5.0 00:00:7.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment