๐ถ Download YouTube Audio as MP3 Using Python
Want to download audio from YouTube and save it as MP3 automatically using Python? This Python script makes it easy — just paste a YouTube URL, and it will:
- Download the best available audio stream ๐ง
- Convert it to MP3 format ๐
- Automatically remove invalid filename characters ๐งน
- Show real-time download progress ๐
Perfect for creating offline playlists, podcast archiving, speech datasets, or extracting background music for editing.
๐งฉ Step 1: Install Required Modules
This script uses three Python libraries:
pytubefix— download YouTube videos/audio.moviepy— convert downloaded audio to MP3.re & os— for handling paths and cleaning filenames.
Install dependencies using pip:
pip install pytubefix moviepy==1.0.3
๐ Step 2: Add the YouTube URL
Replace raw_url in the script with any YouTube link — the script automatically removes extra tracking parameters.
๐ป Step 3: Python Script
Create a file named: youtube_to_mp3.py and paste this code ๐
# Code by: Atul Kushwaha | ChatGPT
import os
import re
import ssl
from pytubefix import YouTube
from pytubefix.cli import on_progress
from moviepy.editor import AudioFileClip
# --- Fix SSL Errors (Sometimes Required) ---
ssl._create_default_https_context = ssl._create_unverified_context
# --- Clean Filename Function ---
def clean_filename(name):
return re.sub(r'[\\/*?:"<>|]', "_", name)
# --- Input URL ---
raw_url = "https://youtu.be/_a2Ijlm-74M?si=YmK5Nz5bzPl1G19e"
raw_url = raw_url.split("?")[0]
# --- Create YouTube Object ---
yt = YouTube(raw_url, on_progress_callback=on_progress)
safe_title = clean_filename(yt.title)
print("\n๐ฌ Title:", yt.title)
print("๐ค Author:", yt.author)
print(f"⏱ Length: {yt.length // 60} min {yt.length % 60} sec\n")
# --- Get Best Available Audio Stream ---
audio_stream = yt.streams.filter(only_audio=True).order_by("abr").desc().first()
if not audio_stream:
print("❌ No audio stream found!")
exit()
temp_filename = f"{safe_title}_temp.mp4"
mp3_filename = f"{safe_title}.mp3"
# --- Download Audio ---
try:
audio_stream.download(filename=temp_filename)
print(f"๐ฅ Downloaded audio stream as: {temp_filename}")
except Exception as e:
print(f"❌ Audio download failed: {e}")
exit()
# --- Convert to MP3 ---
print("\n๐ถ Converting to MP3...")
try:
audio = AudioFileClip(temp_filename)
audio.write_audiofile(mp3_filename)
audio.close()
# Remove temp file
os.remove(temp_filename)
print(f"✅ MP3 saved as: {mp3_filename}")
print("๐งน Temporary file removed.")
except Exception as e:
print(f"❌ MP3 conversion failed: {e}")
⚙️ Step 4: Run the Script
Run this in your terminal:
python youtube_to_mp3.py
The script will download the audio, convert it to MP3, and save it with a clean filename in the same folder.
๐ง How It Works
- Fetches YouTube metadata (title, author, duration).
- Chooses the best available audio bitrate stream automatically.
- Downloads audio as
.mp4for compatibility. - Converts it to MP3 using MoviePy.
- Deletes temporary files after processing.
๐ก Use Cases
- Offline music playlist creation ๐ต
- Podcast voice extraction ๐️
- Sound datasets for machine learning ๐ค
- Background sound collection for editing ๐ฌ
๐ฏ Project Summary
- Language: Python
- Libraries: pytubefix, moviepy
- Output: High-quality .mp3 file
๐ข Join the Community
- Join our WhatsApp channel for more Python projects & automation scripts.
❤️ If this tutorial helped you, share it with others and support the open automation community!
