YouTube Video To Audio Downloader using Python

We often try to download YouTube Videos as Audios alone and for that, we generally end up searching websites that would assist us in doing the same. Subsequently, we find websites crowded with ads and pop-ups. So, How do we create our very own YouTube Video to Audio Downloader? We can do that in Python and we only require two packages for that! How cool right?

This article will guide us in creating our very own YouTube Video to Audio Downloader through a step by step procedure.

  • Installing and Loading the Dependencies Required.
  • Creating a Class AudioDownloaderYouTube.
  • Defining the required methods.

Algorithm

YouTube Video To Audio Downloader using Python

Installing and Loading Dependencies Required

We will be needing a package called youtube_dl which we will be installing using the pip command. This package mainly allows us to download videos from YouTube and a few other websites.

pip install youtube_dl

In addition, we will install ffmpeg, a command-line multimedia framework. We will have to install it explicitly. So, for Windows, we will be downloading the file from here.

  • Go to the link and scroll down to the “release” section.
  • Download the file and extract it to a particular location.
  • Add that location to the PATH environment variable.

Note: If you’re working in a Virtual Environment then copy the contents from the extracted folder (consisting of .exe files, namely “ffmpeg”, “ffplay” and “ffprobe”) and paste it in the “Scripts” folder inside the “venv” folder.

For Mac and Linux users, check out this page for downloading ffmpeg.

We will be loading:

  • YoutubeDL module from youtube_dl
  • os module
# Loading all the packages required
from youtube_dl import YoutubeDL
import os

Creating YouTube to Audio Downloader Class and Defining required methods

We will create a class AudioDownloaderYouTube. Then, we will initialize the variables inside the constructor.

  • url_list will contain the list of the audios to be downloaded.
  • params will contain a dictionary which would be needed inside YoutubeDL
class AudioDownloaderYouTube:

    def __init__(self, url_list):
        self.url_list = url_list
        self.params = None

Defining Methods

set_params()

This method defines a dictionary namely “params”. The dictionary consists of the values for the keys like format, output path, and the postprocessors used. Moreover, the parameters “audio_path” and “format_input” set the values of the output path and preferred audio format. Finally, The value of the instance variable, “params” is set after defining the dictionary.

class AudioDownloaderYouTube:

    def set_params(self, audio_path, format_input='mp3'):
        self.params = {
            'format': 'bestaudio/best',
            'outtmpl': os.path.join(audio_path, '%(title)s.' + format_input),
            'quiet': True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': format_input,
                'preferredquality': '192',
            }]
        }

get_info()

The title of the YouTube video to be downloaded as Audio is extracted by this method. Certainly, we use it mainly to confirm if we will be downloading the correct YouTube Video as Audio.

class AudioDownloaderYouTube:

    def get_info(self):
        with YoutubeDL({'quiet': True}) as audio:
            info = audio.extract_info(self.url_list[0], download=False)
            print('\nTITLE : ', info['title'], '\n')

download()

This method finally downloads the YouTube video as audio and stores it in the specified location/path. In other words, this is the main method.

class AudioDownloaderYouTube:

    def download(self):
        with YoutubeDL(self.params) as audio:
            audio.download(self.url_list)

The main block of  YouTube Video to Audio Downloader .py script

In the main block, we follow the Algorithm mentioned above in the article. To clarify, Firstly, get the link to the YouTube Video. Then, confirm the Title of the Video. After that, get the path of the folder in which the Audio will be downloaded and saved. Finally, get the format of the Audio File.

if __name__ == '__main__':
    # Print a Welcome Message
    print('** YouTube to Audio Downloader **')

    # Setting value of c as 'n' to allow at least one iteration of the loop.
    c = 'n'

    # Looping till user does not enter a link as per his requirement.
    while c != 'y':
        url = input('\nEnter the Link of the YouTube Video: ')

        # Defining an instance of class and passing the URL as a list.
        ady = AudioDownloaderYouTube([url])

        # Obtaining the Title of the YouTube Video.
        ady.get_info()

        # Taking user input.
        c = input('To proceed, press `y`\nIf you want to enter the Link Again, press `n`\n: ')

    # Taking the Path where the Audio is to be downloaded and stored.
    audio_path = input('\nEnter path: ')

    # Available audio formats
    audio_formats = ['mp3', 'wav', 'aac', 'm4a']

    print('Choose a format from: \n\t*-', '\n\t*- '.join(audio_formats))
    format_input = input("Enter format: ")

    # Checking if the user has entered a correct format
    # If not then an exception is raised.
    if format_input in audio_formats:

        # Setting the value of params
        ady.set_params(audio_path, format_input)

        # If the format entered is correct then downloading operation is tried
        # If it fails then an exception is thrown
        try:
            ady.download()
            print('\n*Download Successful!*')
        except:
            print('\nDownload Could not be completed, Try Again!')
    else:
        raise ValueError('Audio Format Entered is Invalid')

Complete Python Code: YouTube Video to Audio Downloader

# Loading all the packages required
from youtube_dl import YoutubeDL
import os


class AudioDownloaderYouTube:

    def __init__(self, url_list):
        self.url_list = url_list
        self.params = None

    def set_params(self, audio_path, format_input='mp3'):
        self.params = {
            'format': 'bestaudio/best',
            'outtmpl': os.path.join(audio_path, '%(title)s.' + format_input),
            'quiet': True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': format_input,
                'preferredquality': '192',
            }]
        }

    def get_info(self):
        with YoutubeDL({'quiet': True}) as audio:
            info = audio.extract_info(self.url_list[0], download=False)
            print('\nTITLE : ', info['title'], '\n')

    def download(self):
        with YoutubeDL(self.params) as audio:
            audio.download(self.url_list)


if __name__ == '__main__':
    # Print a Welcome Message
    print('** YouTube to Audio Downloader **')

    # Setting value of c as 'n' to allow at least one iteration of the loop.
    c = 'n'

    # Looping till user does not enter a link as per his requirement.
    while c != 'y':
        url = input('\nEnter the Link of the YouTube Video: ')

        # Defining an instance of class and passing the URL as a list.
        ady = AudioDownloaderYouTube([url])

        # Obtaining the Title of the YouTube Video.
        ady.get_info()

        # Taking user input.
        c = input('To proceed, press `y`\nIf you want to enter the Link Again, press `n`\n: ')

    # Taking the Path where the Audio is to be downloaded and stored.
    audio_path = input('\nEnter path: ')

    # Available audio formats
    audio_formats = ['mp3', 'wav', 'aac', 'm4a']

    print('Choose a format from: \n\t*-', '\n\t*- '.join(audio_formats))
    format_input = input("Enter format: ")

    # Checking if the user has entered a correct format
    # If not then an exception is raised.
    if format_input in audio_formats:

        # Setting the value of params
        ady.set_params(audio_path, format_input)

        # If the format entered is correct then downloading operation is tried
        # If it fails then an exception is thrown
        try:
            ady.download()
            print('\n*Download Successful!*')
        except:
            print('\nDownload Could not be completed, Try Again!')
    else:
        raise ValueError('Audio Format Entered is Invalid')

Console Input and Output

YouTube Video To Audio Downloader using Python

You have reached the end of this article. Cheers! Certainly, You should check these other articles as well:

Leave a Reply

Your email address will not be published. Required fields are marked *