12
votes

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.

10

10 Answers

8
votes

How can I download the video as an audio file, in .mp3 format directly?

I'm afraid you can't. The only files available for direct download are the ones which are listed under yt.streams.all().

However, it is straightforward to convert the downloaded audio file from .mp4 to .mp3 format. For example, if you have ffmpeg installed, running this command from the terminal will do the trick (assuming you're in the download directory):

$ ffmpeg -i downloaded_filename.mp4 new_filename.mp3

Alternatively, you can use Python's subprocess module to execute the ffmpeg command programmatically:

import os
import subprocess

import pytube

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: "))

parent_dir = r"C:\YTDownloads"
vids[vnum].download(parent_dir)

new_filename = input("Enter filename (including extension): "))  # e.g. new_filename.mp3

default_filename = vids[vnum].default_filename  # get default name using pytube API
subprocess.run([
    'ffmpeg',
    '-i', os.path.join(parent_dir, default_filename),
    os.path.join(parent_dir, new_filename)
])

print('done')

EDIT: Removed mention of subprocess.call. Use subprocess.run (unless you're using Python 3.4 or below)

4
votes

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.

2
votes

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.

1
votes

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')
1
votes

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()
1
votes

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.

0
votes

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.

0
votes
from pytube import YouTube

yt = YouTube(url)

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

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")
0
votes

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 file
video.streams.filter(only_audio = True).first().download(path)
# convert mp4 to mp3
my_file  = path+ "\\" + str(video.title)+ ".mp4"
base = os.path.splitext(my_file)[0]
os.rename(my_file, base + '.mp3')
print(video.title, ' has been successfully downloaded')