DEV Community

Cover image for YouTube to MP3 Downloader | Rookie Week of Python Day 04

YouTube to MP3 Downloader | Rookie Week of Python Day 04

hannankhan profile image Hannan ・2 min read

Who doesn't love YouTube downloaders and MP3 conversion sites? They were the backbone of every teen's MP3 player library not too long ago, before Spotify or Apple Music, but have you ever wondered how these sites worked? In this tutorial we will create a python script to create our very own YouTube to MP3 convertor so you too can download your favourite videos and podcasts in audio form


Technically, it is not illegal to convert a YouTube video to MP3 - but it is illegal to download a copyrighted music video.

YouTube to Audio Converter/Downloader

first of all we will need two prerequisites for this program. We need to pip install the youtube_dl library and the latest ffmpeg build for your specific operating system.

pip install youtube_dl

now to import the libraries needed for the program

import youtube_dl
import sys
Enter fullscreen mode Exit fullscreen mode

declare a variable ydl_opts (in this case) to specify the specifications of the file you want to download. in this case we will select the format to be the best audio format available, the prefferedcodec will be mp3 and the rest can be left as default as shown here.

ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
Enter fullscreen mode Exit fullscreen mode

Write an if statement to download the file and pass the values of the ydl_opts variable to youtube_dl

if __name__ == "__main__":
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        filenames = sys.argv[1:]
Enter fullscreen mode Exit fullscreen mode

Run your command terminal and execute the python program and append the command line with the URL of any YouTube video (make sure to include "https://").

python <URL>

Run the program and if everything goes smoothly you should see the following output:
Alt Text
The MP3 file will appear in the same directory as your program. Since my program is on my desktop you can see the downloaded file here.
Alt Text

Thanks for reading, you can find the code on it's GitHub repo here.

Discussion (0)

Editor guide