Skip to content

Instantly share code, notes, and snippets.

@matthewraaff
Last active December 18, 2023 14:18
Show Gist options
  • Save matthewraaff/b456d999acaaa35aeff542416ed2c319 to your computer and use it in GitHub Desktop.
Save matthewraaff/b456d999acaaa35aeff542416ed2c319 to your computer and use it in GitHub Desktop.
youtube music downloader
from pytube import YouTube, Playlist
import os
from datetime import timedelta
def download_audio(video_url, output_path='music'):
yt = YouTube(video_url)
audio_stream = yt.streams.filter(only_audio=True, file_extension='mp4').first()
os.makedirs(output_path, exist_ok=True)
audio_stream.download(output_path)
print("Download complete!")
def download_playlist(playlist_url, output_path='music'):
playlist = Playlist(playlist_url)
os.makedirs(output_path, exist_ok=True)
for video_url in playlist.video_urls:
download_audio(video_url, output_path)
with open('download.txt', 'r') as file:
video_urls = file.read().splitlines()
total_duration = 0
for url in video_urls:
if 'youtube.com/playlist' in url:
playlist = Playlist(url)
for video_url in playlist.video_urls:
yt = YouTube(video_url)
total_duration += yt.length
download_audio(video_url)
else:
yt = YouTube(url)
total_duration += yt.length
download_audio(url)
total_duration = timedelta(seconds=total_duration)
print(f"Total run time: {total_duration}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment