Download YouTube Video as MP3 using Python

Today, Youtube is the second most popular social media site. People are using it to watch, add, and simply entertain themselves through video content.
You must have already tried to download Youtube videos with the help of various third-party applications. However, in this tutorial, you will learn how to download Youtube videos in mp3 format by making use of Python.

Python provides 2 ways for downloading Youtube videos as mp3, both of which you shall see below.

Using youtube-dl

“youtube-dl” is a free, open-source command-line program that you can use to download youtube videos as well as videos from some other sites. It requires a Python version 2.6 and above and supports all operating systems.

Install youtube_dl in Python

First of all, install the youtube-dl by typing the following command on the terminal.

pip install youtube_dl

Download Youtube Video in MP3 format using youtube_dl in Python

Once you install youtube-dl, you can start downloading as follows:

  • We first import youtube-dl to our program and then define the function download_ytvid_as_mp3 for the process of downloading.
  • We read the URL of the video that we want to download.
  • Then, the extract_info extracts all the information about the video(upload date, views,  likes, dislikes, title, format, duration etc) whose link we provide as a parameter.
  • Further, we must specify the file format in which we want to download it, mp3 in our case. You can specify the name and extension under which it is to be saved by using f-strings or other concatenation methods as shown.
  • You must be aware that mp3 handles only one type of media, i.e., the audio file.
    We then specify the formatting and output template options for the same, as needed.
  • Once we have specified all the suitable parameters, we invoke the youtube_dl’s download(), to download the mp3 file.
import youtube_dl
def download_ytvid_as_mp3():
    video_url = input("enter url of youtube video:")
    video_info = youtube_dl.YoutubeDL().extract_info(url = video_url,download=False)
    filename = f"{video_info['title']}.mp3"
    options={
        'format':'bestaudio/best',
        'keepvideo':False,
        'outtmpl':filename,
    }

    with youtube_dl.YoutubeDL(options) as ydl:
        ydl.download([video_info['webpage_url']])

    print("Download complete... {}".format(filename))
download_ytvid_as_mp3()
enter url of youtube video:https://www.youtube.com/watch?v=ifUxQYsmSf8
[youtube] ifUxQYsmSf8: Downloading webpage
[youtube] ifUxQYsmSf8: Downloading webpage
[download] Destination: My Engagement Solo Dance!! Achyutam Keshavam, Radha.mp3
[download] 100% of 3.25MiB in 01:12                 
Download complete... My Engagement Solo Dance!! Achyutam Keshavam, Radha.mp3

You will notice that the mp3 file is downloaded and present in the current directory itself.

Using pytube

“pytube” is a library written in Python to facilitate the downloading of youtube videos.
To download youtube videos as mp3 using pytube, first of all, make sure to install the pytube library. You can do this by running the following command on the terminal.

pip install pytube

Download Youtube video from URL in MP3 format using Pytube in Python

Given below is the simple code, for downloading the audio file of a youtube video.

import pytube as pt

yt = pt.YouTube("https://www.youtube.com/watch?v=FjHGZj2IjBk")
t = yt.streams.filter(only_audio=True)
t[0].download()
'C:\\Users\\varsh\\Desktop\\filename.mp4'

However, the issue here is that though it downloads only the audio file as specified in the filter, it saves the file in mp4 method. So, let us make some modifications to enable storing it in mp3 mode.
To facilitate the storing of the audio file in mp3 format, we make use of the operating system module(os).

  • Just like in the previous method, we read the URL of the video file.
  • Once this is done, we use the streams.filter() to ensure that only the audio file is extracted.
  • Further, we ask the user for the destination address in which he/she wants to save the file and then invoke the download().
  • Though this downloads just the audio file, it doesn’t save it in mp3 format as told earlier. Hence, we use methods of the os library as shown.
    The os.path.splittext() splits the pathname into root/name and extension.
  • By utilizing this, we rename the file with an mp3 extension.
from pytube import YouTube
import os
yt = YouTube(str(input("Enter URL of youtube video: \n ")))
video = yt.streams.filter(only_audio=True).first()
print("Enter the destination address (leave blank to save in current directory)")
destination = str(input(" ")) or '.'
out_file = video.download(output_path=destination)
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
print(yt.title + " has been successfully downloaded.")
Enter URL of youtube video: 
https://www.youtube.com/watch?v=BVXRhiPCzdI
Enter the destination address (leave blank to save in current directory)
 
Daily Move: Coffee Break Stretch has been successfully downloaded.

Thus, the audio file of the youtube video whose link you specify will be downloaded in mp3 format.

Now, aren’t you curious about how to download youtube videos using Python? If yes, do read,
Downloading YouTube video using Python to a certain directory

Leave a Reply

Your email address will not be published.