Download video in mp3 format using pytube

Viewed 41283

I have been using pytube to download youtube videos in python. So far I have been able to download in mp4 format.

yt = pytube.YouTube("https://www.youtube.com/watch?v=WH7xsW5Os10")

vids= yt.streams.all()
for i in range(len(vids)):
    print(i,'. ',vids[i])

vnum = int(input("Enter vid num: "))
vids[vnum].download(r"C:\YTDownloads")
print('done')

I managed to download the 'audio' version, but it was in .mp4 format. I did try to rename the extension to .mp3, and the audio played, but the application (Windows Media Player) stopped responding and it began to lag.

How can I download the video as an audio file, in .mp3 format directly? Please provide some code as I am new to working with this module.

14 Answers

I am assuming you are using Python 3 and pytube 9.x, you can use the filter method to "filter", the file extension you are interested in.

For example, if you would like to download mp4 video file format it would look like the following:

pytube.YouTube("url here").streams.filter(file_extension="mp4").first()

if you would like to pull audio it would look like the following:

pytube.YouTube("url here").streams.filter(only_audio=True).all()

Hope that helps anyone landing on this page; rather than converting unnecessarily.

Pytube does not support "mp3" format but you can download audio in webm format. The following code demonstrates it.

    from pytube import YouTube
    yt = YouTube("https://www.youtube.com/watch?v=kn8ZuOCn6r0")
    stream = yt.streams.get_by_itag(251)

the itag is unique id to get file with sppecific resolution

    stream.download()

For mp3 you have to convert (mp4 or webm) file format to mp3.

With this code you will download all the videos from a playlist and saving them with the title from youtube in mp4 and mp4 audio formats.

i used the code from @scrpy in this question and the hint from @Jean-Pierre Schnyder from this answer

import os
import subprocess
import re
from pytube import YouTube
from pytube import Playlist


path =r'DESTINATION_FOLER'
playlist_url = 'PLAYLIST_URL'

play = Playlist(playlist_url)

play._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
print(len(play.video_urls))
for url in play.video_urls:
    yt = YouTube(url)
    audio = yt.streams.get_audio_only()
    audio.download(path)
    nome = yt.title
    new_filename=nome+'.mp3'
    default_filename =nome+'.mp4'
    ffmpeg = ('ffmpeg -i ' % path default_filename + new_filename)
    subprocess.run(ffmpeg, shell=True)
         
    
print('Download Complete')

You will need to install pytubemp3 (using pip install pytubemp3) latest version 0.3 + then

from pytubemp3 import YouTube 
YouTube(video_url).streams.filter(only_audio=True).first().download()

Download the video as audio, then just change the audio extension to MP3:

from pytube import YouTube
import os

url = str(input("url:- "))
yt = YouTube(url)
video = yt.streams.filter(only_audio=True).first()
downloaded_file = video.download()
base, ext = os.path.splitext(downloaded_file)
new_file = base + '.mp3'
os.rename(downloaded_file, new_file)
print("Done")

Pytube does not support "mp3" format but you can download audio in webm format. The following code demonstrates it.

    from pytube import YouTube
    yt = YouTube("https://www.youtube.com/watch?v=kn8ZuOCn6r0")
    stream = yt.streams.get_by_itag(251)
    stream.download()

For mp3 you have to convert (mp4 or webm) file format to mp3.

here is a mildly more slim and dense format for downloading an mp4 video and converting from mp4 to mp3:

Download will download the file to the current directory or location of the program, this will also convert the file to mp3 as a NEW file.

from pytube import YouTube
import os
import subprocess
import time

while True:
    url = input("URL: ")

    # Title and Time
    print("...")
    print(((YouTube(url)).title), "//", (int(var1)/60),"mins")
    print("...")

    # Filename specification
    # Prevents any errors during conversion due to illegal characters in name
    _filename = input("Filename: ")

    # Downloading
    print("Downloading....")
    YouTube(url).streams.first().download(filename=_filename)
    time.sleep(1)

    # Converting
    mp4 = "'%s'.mp4" % _filename
    mp3 = "'%s'.mp3" % _filename
    ffmpeg = ('ffmpeg -i %s ' % mp4 + mp3)
    subprocess.call(ffmpeg, shell=True)

    # Completion
    print("\nCOMPLETE\n")

This is an infinite loop that will allow the renaming, download, and conversion of multiple URLs.

from pytube import YouTube

yt = YouTube(url)

yt.streams.get_audio_only().download(output_path='/home/',filename=yt.title)

This is my solution:

import os
import sys
from pytube import YouTube
from pytube.cli import on_progress

PATH_SAVE = "D:\Downloads"

yt = YouTube("YOUR_URL", on_progress_callback=on_progress)
#Download mp3
audio_file = yt.streams.filter(only_audio=True).first().download(PATH_SAVE)
base, ext = os.path.splitext(audio_file)
new_file = base + '.mp3'
os.rename(audio_file, new_file)

#Download Video
ys = yt.streams.filter(res="1080p").first()
ys.download(PATH_SAVE)

Working: Python v3.9.x and pytube v11.0.1

try to use :


    from  pytube import YouTube
    import os
        
    link = input('enter the link: ')
    path = "D:\\"                     #enter the path where you want to save your video
    video = YouTube(link)
    print( "title is : ", video.title)
     
#download video

    print("title is : ", video.title)
    video.streams.filter(only_audio=True).first().download( path , filename ="TemporaryName.Mp4" )

#remove caracters (" | , / \ ..... ) from video title

    VideoTitle =  video.title
    VideoTitle = VideoTitle.replace('\"' , " ")
    VideoTitle = VideoTitle.replace('|', " ")
    VideoTitle = VideoTitle.replace(',', " ")
    VideoTitle = VideoTitle.replace('/"' , " ")
    VideoTitle = VideoTitle.replace('\\', " ")
    VideoTitle = VideoTitle.replace(':', " ")
    VideoTitle = VideoTitle.replace('*"' , " ")
    VideoTitle = VideoTitle.replace('?', " ")
    VideoTitle = VideoTitle.replace('<', " ")
    VideoTitle = VideoTitle.replace('>"' , " ")

#change name and converting Mp4 to Mp3

    my_file = path + "\\" +  "TemporaryName.mp4"
    base = path + "\\" + VideoTitle
    print("New Video Title is :" +VideoTitle)
    os.rename(my_file, base + '.mp3')
    print(video.title, ' \nhas been successfully downloaded as MP3')

This is my solution:

from os import path, rename
from pytube import YouTube as yt

formato = ""
descarga = desktop = path.expanduser("~/Desktop")
link = input("Inserte el enlace del video: ")
youtube = yt(link)
while formato != "mp3" and formato != "mp4":
    formato = input("¿Será en formato mp3 o mp4? ")


if formato == "mp4":

    youtube.streams.get_highest_resolution().download(descarga)

elif formato == "mp3":

    video = youtube.streams.first()
    downloaded_file = video.download(descarga)
    base, ext = path.splitext(downloaded_file)
    new_file = base + '.mp3'
    rename(downloaded_file, new_file)

print("Descarga completa!")

input("Presiona Enter para salir...")

Here is my solution. Just rename downloaded content's name with pytube's filename option.

url = input("URL of the video that will be downloaded as MP^: ")
  try:
    video = yt(url)
    baslik = video.title
    print(f"Title: {baslik}")
    loc = input("Location: ")
    print(f"Getting ITAG info for {baslik}")
    for itag in video.streams.filter(only_audio=True): # It'll show only audio streams.
      print(itag)
    itag = input("ITAG secimi: ")
    print(f"{baslik} sesi {loc} konumuna indiriliyor.")
    video.streams.get_by_itag(itag).download(loc, filename=baslik + ".mp3") # And you can rename video by filename= option. Just add .mp3 extension to video's title.
    print("Download finished.")
  except:
    print("Enter a valid URL")
    sys.exit()

This worked very well for me:

pip install pytube
pip install os_sys

# importing packages
from pytube import YouTube
import os
  
# url input from user
yt = YouTube(
    str(input("paste your link")))
  
# extract only audio
video = yt.streams.filter(only_audio=True).first()
  
# check for destination to save file
print("Enter the destination (leave blank for current directory)")
destination = str(input(">> ")) or '.'
  
# download the file
out_file = video.download(output_path=destination)
  
# save the file
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
  
# result of success
print(yt.title + " has been successfully downloaded.")
Related