Last active
May 4, 2025 04:15
-
-
Save ayubmetah/a45102d087b6a2dbcd9d60412204d003 to your computer and use it in GitHub Desktop.
Script to Download High Quality Youtube mp3 audio from Videos.
This file contains hidden or 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
import os | |
import re | |
import yt_dlp | |
from moviepy import AudioFileClip | |
def sanitize_filename(filename): | |
"""Remove invalid characters from filename""" | |
return re.sub(r'[\\/*?:"<>|]', "", filename) | |
def download_youtube_as_mp3(url, output_path=".", bitrate="320k"): | |
try: | |
# Create output directory if it doesn't exist | |
os.makedirs(output_path, exist_ok=True) | |
ydl_opts = { | |
'format': 'bestaudio/best', | |
'outtmpl': os.path.join(output_path, '%(title)s.%(ext)s'), | |
'postprocessors': [{ | |
'key': 'FFmpegExtractAudio', | |
'preferredcodec': 'mp3', | |
'preferredquality': bitrate[:-1], # Remove 'k' from bitrate | |
}], | |
'quiet': True, | |
} | |
with yt_dlp.YoutubeDL(ydl_opts) as ydl: | |
info = ydl.extract_info(url, download=False) | |
print(f"Downloading: {info['title']}...") | |
ydl.download([url]) | |
# Find the downloaded file | |
original_filename = ydl.prepare_filename(info) | |
mp3_filename = os.path.splitext(original_filename)[0] + '.mp3' | |
mp3_filename = sanitize_filename(mp3_filename) | |
print(f"Successfully downloaded and converted to MP3 ({bitrate}): {mp3_filename}") | |
return mp3_filename | |
except Exception as e: | |
print(f"An error occurred: {e}") | |
return None | |
if __name__ == "__main__": | |
# Get YouTube URL from user input | |
youtube_url = input("Enter YouTube URL: ").strip() | |
# Ask for output directory (optional) | |
output_dir = input("Enter output directory (press Enter for current directory): ").strip() | |
if not output_dir: | |
output_dir = "." | |
# Download and convert | |
download_youtube_as_mp3(youtube_url, output_dir) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To install plugins, run below script in elevated Powershell.
Then,