Skip to content

Instantly share code, notes, and snippets.

@apkatsikas
Last active January 13, 2024 17:43
Show Gist options
  • Save apkatsikas/f6c843a78c7017b1b05ed95cf35b2b27 to your computer and use it in GitHub Desktop.
Save apkatsikas/f6c843a78c7017b1b05ed95cf35b2b27 to your computer and use it in GitHub Desktop.
Download a portion of a youtube using yt-dlp and ffmpeg - requires Python 3, yt-dlp and ffmpeg (all must be on the path)
import argparse
import subprocess
import sys
def create_parser():
p = argparse.ArgumentParser()
p.add_argument('url', help='youtube URL', nargs='?')
p.add_argument('-ss', '--seek', help='position in time to start at', default='00:00:00')
p.add_argument('-t', '--time', help='time of clip/duration', default='00:00:01')
p.add_argument('-o', '--output', help='output file name', default='output.mp4')
p.add_argument(
'-p', '--path',
help='full or relative path for source and destination',
default='/mnt/c/Users/apkat/Videos'
)
return p
if __name__ == '__main__':
parser = create_parser()
args = parser.parse_args()
if not args.url:
parser.print_help()
sys.exit(0)
# Setup command for youtube-dl
yt_dl_cmd = ['yt-dlp', '--youtube-skip-dash-manifest', '-g', args.url]
# Run youtube-dl command
result = subprocess.run(yt_dl_cmd, stdout=subprocess.PIPE, universal_newlines=True)
# Split resultant URLs on new lines
urls = result.stdout.splitlines()
if len(urls) > 1 and urls[1] != '':
# FFmpeg options for mapping audio and video
ff_options = '-map 0:v -map 1:a -c:v libx264 -c:a aac'
# Assemble full command
ff_cmd = 'ffmpeg -y -ss {} -i "{}" -ss {} -i "{}" -t {} {} {}/{}'.format(
args.seek, urls[0], args.seek, urls[1], args.time, ff_options, args.path, args.output)
else:
ff_options = '-c:v libx264 -c:a aac'
ff_cmd = 'ffmpeg -y -ss {} -t {} -i {} {} {}/{}'.format(
args.seek, args.time, urls[0], ff_options, args.path, args.output)
# Run FFmpeg command
subprocess.call(ff_cmd, shell=True)
@apkatsikas
Copy link
Author

Usage looks like python3 yt-dl.py "https://www.youtube.com/watch?v=1234" -ss 00:16:06 -t 00:00:04 -o test.mp4

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