Download Video in MP3 format using PyTube


Pytube is a Python library that is used to download any youtube video easily. It offers a simple and intuitive interface, making it easy to use even for those who are not familiar with programming. It provides the option to download a video in various formats like mp4,mp3,3gp,webm, etc. In this article, we will learn step by step process of how to download the video in mp3 format using Pytube.

Install Pytube

Before using the Pytube module we need to download the Pytube library in our system by using the Python package manager. To download the Pytube module type the following command in your terminal or command prompt.

pip install pytube

Downloading a YouTube Video in MP3 Format

Follow the following steps to download the youtube video in mp3 format.

Step 1: Import the necessary modules

First, import the necessary modules in your Python script. We will be using the pytube module to download the video.

from pytube import YouTube

Step 2: Create a YouTube object

Create a YouTube object by passing the URL of the YouTube video that you want to download. In this example, we will be downloading "The Last Butterfly - Beautiful Sad Piano Violin Music" song.

url = "https://www.youtube.com/watch?v=ZTrrc6Ni5eM"
video = YouTube(url)

Step 3: Download the video and convert to mp3

Call the streams.filter() method to filter out the streams that we don't need, and then call the first() method to select the first available stream. We will be changing the name of the file to a .mp3 extension.

stream = video.streams.filter(only_audio=True).first()
stream.download(filename=f"{video.title}.mp3")

Step 4: Complete code using error handling

Sometimes while downloading a video the URL of the video might be incorrect or there is some network error. These errors need to be handled using the try-except block in python.

Code

from pytube import YouTube

url = "https://www.youtube.com/watch?v=ZTrrc6Ni5eM"

try:
   video = YouTube(url)
   stream = video.streams.filter(only_audio=True).first()
   stream.download(filename=f"{video.title}.mp3")
   print("The video is downloaded in MP3")
except KeyError:
   print("Unable to fetch video information. Please check the video URL or your network connection.")

Output

The video is downloaded in MP3

Conclusion

In this article, we discussed how we can download a video in mp3 format using the PyTube library in Python.PyTube makes it easy to download videos from YouTube, and the moviepy module provides an easy way to convert the downloaded video to MP3 format. Pytube library helps us to download any youtube video in any format. It has an easy-to-use syntax and can also be used to download any video in mp3 format i.e. audio-only.

Updated on: 10-Jul-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements