Last active
September 30, 2021 21:14
-
-
Save ranelpadon/cce767de058f75a0730c0558dc761ab7 to your computer and use it in GitHub Desktop.
YouTube Downloader and Trimmer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Add this to your `~/.bash_profile` or `~/.zshrc` file, | |
# so that running the Python script in the terminal is more convenient. | |
# Command: yvt URL START_TIME END_TIME | |
# Sample: yvt 'https://www.youtube.com/watch?v=RjxKVAOZCQY' 9:41 10:58 | |
yt_video_trimmer() { | |
python <PATH TO>/yt-video-trimmer.py $1 $2 $3 | |
} | |
alias yvt=yt_video_trimmer |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Needs PyTube (downloader) and MoviePy (trimmer) libraries. | |
$ pip install pytube | |
$ pip install moviepy | |
""" | |
import os | |
from sys import argv | |
from moviepy.editor import VideoFileClip | |
from pytube import YouTube | |
URL = argv[1] | |
start_time_components = argv[2].split(':') | |
start_time_minutes = int(start_time_components[0]) * 60 # Convert to seconds | |
start_time_seconds = float(start_time_components[1]) | |
START_TIME = start_time_minutes + start_time_seconds | |
end_time_components = argv[3].split(':') | |
end_time_minutes = int(end_time_components[0]) * 60 # Convert to seconds | |
end_time_seconds = float(end_time_components[1]) | |
END_TIME = end_time_minutes + end_time_seconds | |
FILE_NAME_DOWNLOADED_VIDEO = 'downloaded_video.mp4' | |
FILE_NAME_TRIMMED_VIDEO = 'trimmed_video.mp4' | |
print('\nDownloading video...') | |
# API: https://pytube.io/en/latest/api.html | |
yt_video = YouTube(URL) | |
# Downloads the `progressive=True` variant which bundles both the video and audio. | |
# `progressive=False` has better resolution but requires merging video and audio using FFMPEG. | |
yt_video.streams.get_highest_resolution().download(filename=FILE_NAME_DOWNLOADED_VIDEO) | |
print('\nTrimming video...') | |
# API: https://zulko.github.io/moviepy/ref/ref.html | |
# https://zulko.github.io/moviepy/ref/Clip.html#moviepy.Clip.Clip.subclip | |
clip = VideoFileClip(FILE_NAME_DOWNLOADED_VIDEO) | |
trimmed_video = clip.subclip(START_TIME, END_TIME) | |
trimmed_video.write_videofile(FILE_NAME_TRIMMED_VIDEO) | |
print('\nRemoving downloaded video...') | |
os.remove(FILE_NAME_DOWNLOADED_VIDEO) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment