Skip to content

Instantly share code, notes, and snippets.

@truevis
Last active April 30, 2024 19:36
Show Gist options
  • Select an option

  • Save truevis/2a070a9694f3b83e72952534c0d7292e to your computer and use it in GitHub Desktop.

Select an option

Save truevis/2a070a9694f3b83e72952534c0d7292e to your computer and use it in GitHub Desktop.
Downloads and saves YouTube audio streams using pytube
import re
from pytube import YouTube
def download_youtube_audio(url):
yt = YouTube(url)
audio_stream = yt.streams.filter(only_audio=True).first()
# Remove invalid characters from the filename using regex
cleaned_title = re.sub(r'[<>:"/\\|?*]', '_', yt.title)
print(f"Downloading audio from: {yt.title}")
filename=f"d:/Downloads/{cleaned_title}.mp3"
audio_stream.download(filename=filename)
print(f"Downloaded to: <{filename}>")
video_url = "https://www.youtube.com/watch?v=v-123"
download_youtube_audio(video_url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment