Python Magic: Transforming YouTube Videos into MP3s with Ease

ifeelfree
2 min readMar 24, 2024
unsplash.com

I endure a lengthy commute daily and try to utilize offline MP3 audio from YouTube when I am on the train. Then, a question arises: can I download Youtube videos to MP3s with Python?

Several Python libraries facilitate downloading YouTube videos as MP3 audio files. Noteworthy among these are youtube_dl, pytube, and youtube-search-python, etc. Among them, pytube stands out not only for its simplicity but also for its high success rate. Below is a concise procedure:

Step 1: Ensure Python is installed on your computer. Refer to tutorials for guidance on Python installation.

Step 2: Preferably, use Python version (≥3.8) as pytube is compatible with these versions.

Step 3: Install pytube: pip install pytube.

Step 4: Generate the following Python script file transform_youtube_mp3.py:

from pytube import YouTube
import os

# Step 1: Get the YouTube video
yt = YouTube(str(input("Enter the video's URL:\n>> ")))

video = yt.streams.filter(only_audio=True).first()

# Step 2: Specify destination
print("Enter the destination (leave blank for current directory)")
destination = str(input(">> ")) or '.'

# Step 3: Download the file
out_file = video.download(output_path=destination)

# Step 4: Rename the downloaded file
base, ext =…

--

--