Download YouTube Audio as MP3 Using Python

๐ŸŽถ 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 .mp4 for 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

❤️ If this tutorial helped you, share it with others and support the open automation community!

Previous Post Next Post

Contact Form