Skip to content

Instantly share code, notes, and snippets.

@ytensor42
Last active March 18, 2025 08:19
Show Gist options
  • Save ytensor42/f19bd804a941b9deccc2c079c3bcc42e to your computer and use it in GitHub Desktop.
Save ytensor42/f19bd804a941b9deccc2c079c3bcc42e to your computer and use it in GitHub Desktop.
Youtube to mp3
#!<your python3 path>
#
# ymp3.py
# ; Download youtube contents and convert into mp3
# ; Prerequisite: pytube, ffmpeg
#
#
import subprocess
import argparse
import os
from pytube import YouTube
def argument_process():
parser = argparse.ArgumentParser()
parser.add_argument( 'url', help = 'youtube url to download' )
parser.add_argument( '-n', '--name', default = 'notitle', help = 'file root name' )
parser.add_argument( '-l', '--stream', default = False, action = "store_true", help = 'show all available stream' )
parser.add_argument( '-i', '--itag', default = '251', help = 'specify target stream itag' )
parser.add_argument( '-f', '--preserve', default = False, action = "store_true", help = 'do not delete after mp3 conversion' )
parser.add_argument( '-d', '--download', default = True, action = "store_true", help = 'download target content' )
parser.add_argument( '-s', '--skipdownload', default = False, action = "store_true", help = 'skip download' )
parser.add_argument( '-3', '--mp3', default = True, action = "store_true", help = 'produce mp3' )
args = parser.parse_args()
try:
yt = YouTube(args.url)
except:
print( 'error: Youtube URL {} is not accessible'.format(args.url) )
exit(1)
else:
return yt, args
def main():
yt, args = argument_process()
if args.stream:
for s in yt.streams.all():
print(s)
exit(1)
if args.download and not args.skipdownload:
stream = yt.streams.get_by_itag(args.itag)
stream.download(filename=args.name)
if args.mp3:
subprocess.run([ "ffmpeg", "-i", "{}.webm".format(args.name), "-b:a", "160k", "-vn", "{}.mp3".format(args.name) ])
if not args.preserve and os.path.exists("{}.webm".format(args.name)):
os.remove("{}.webm".format(args.name))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment