Download video in mp3 format using pytube
Asked Answered
A

16

25

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.

Aurify answered 21/11, 2017 at 18:35 Comment(0)
E
21

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)

Extravagant answered 12/12, 2017 at 12:35 Comment(8)
Thanks, but how can I do this in Python (3.4)?Aurify
Is it possible to pipe audio from pytube to ffmpeg so downloading and conversion could happen in parallel?Lorineloriner
No idea, sorry! But I would imagine that in most cases the time spent downloading would be much greater than the time spent converting, so you wouldn't gain much overall by parallelising anyway.Extravagant
For me both of them are slow (conversion being slowest). Anyway, I figured it out. You need to download the content in chunks while immediately passing each downloaded chunk to ffmpeg for processing alongside. I posted an example gist at gist.github.com/ritiek/c98452d8dcf062a63a70fe4631099419 I noticed a considerable decrease in overall time taken on my side (good thing), given my hardware specs and internet speed.Lorineloriner
Very nice gist! Can you provide some timing results comparing the serial method with your chunking approach? I'm interested to see what the difference is...Extravagant
I've updated the gist to include both sequential and parallel processing. Running the gist on my RPi Zero and benchmarking with $ time python3 code.py- Sequentially I got python3 code.py 43.95s user 2.67s system 54% cpu 1:25.18 total and parallely I got 44.53s user 2.16s system 84% cpu 55.071 total. Total time taken reduces by 35% in parallel processing which is pretty good.Lorineloriner
@CrazyVideoGamez Have you tried? Did it work? AFAIK it won't work, see my comment on this answer belowExtravagant
@Extravagant I have tried, and the browser displayed correctly as an audio fileYerkovich
S
8

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.

Sulcate answered 30/7, 2019 at 4:21 Comment(4)
This is good to know, thanks @AlgoLamda. However, I think the OP's question boils down to "how can I download an audio file in mp4 format directly as an audio file in mp3 format", to which the answer is: you can't, you have to convert it. This is because mp3 is an audio only format, whereas an mp4 is a "digital multimedia container" format, and so an audio only mp4 file is still audio in a container, and not the same as an mp3.Extravagant
It's YouTube, not YoutubeYerkovich
Tried it and it did download it but coudnt play it then.Restaurant
That isn't always a good idea to skip converting. I was doing this and just renaming the audio only mp4 to mp3. It worked on most programs but I had problems with discord Pydub when I tried to play it. Missing headers that are caused by renaming instead of converting.Purificator
C
3

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')
Calyx answered 5/8, 2020 at 16:37 Comment(0)
H
3

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()
Hussar answered 24/8, 2020 at 0:45 Comment(1)
this will download the audio but with .mp4 extension, he wants it with mp3 extension.Foggy
T
3

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")
Tall answered 2/5, 2021 at 10:53 Comment(0)
G
3

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.

Garate answered 9/6, 2021 at 16:17 Comment(0)
E
1

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.

Entozoic answered 1/12, 2018 at 3:42 Comment(0)
V
1
from pytube import YouTube

yt = YouTube(url)

yt.streams.get_audio_only().download(output_path='/home/',filename=yt.title)
Viewpoint answered 15/3, 2021 at 8:49 Comment(1)
Please, add explaination.Canaanite
L
1

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.

Lourdeslourie answered 2/5, 2021 at 11:30 Comment(0)
N
1

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

Neom answered 28/10, 2021 at 16:54 Comment(0)
A
0

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')
Advised answered 4/8, 2021 at 21:53 Comment(0)
T
0

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...")
Telecast answered 4/12, 2021 at 23:15 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Contortionist
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewBravar
S
0

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()
Sessler answered 1/1, 2022 at 15:32 Comment(0)
A
0

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.")
Aquarius answered 17/6, 2022 at 22:43 Comment(0)
Q
0

Here is the function that downloads music in the highest available quality using pytube and saves it in desired directory.

from pytube import YouTube
import os
from pathlib import Path


def youtube2mp3 (url,outdir):
    # url input from user
    yt = YouTube(url)

    ##@ Extract audio with 160kbps quality from video
    video = yt.streams.filter(abr='160kbps').last()

    ##@ Downloadthe file
    out_file = video.download(output_path=outdir)
    base, ext = os.path.splitext(out_file)
    new_file = Path(f'{base}.mp3')
    os.rename(out_file, new_file)
    ##@ Check success of download
    if new_file.exists():
        print(f'{yt.title} has been successfully downloaded.')
    else:
        print(f'ERROR: {yt.title}could not be downloaded!')
Quip answered 28/11, 2022 at 1:28 Comment(0)
T
0

I have a more Pythonic way to download YouTube videos as MP3 using PyTube:

# Use PyTube to download a YouTube video, then convert to MP3 (if needed) using MoviePy
import pytube
from moviepy.editor import AudioFileClip

link = "your youtube link here"
fn = "myfilename.mp3"

yt = pytube.YouTube(str(link))
video = yt.streams.filter(only_audio=True).first()
out_file = video.download(output_path='.')
os.rename(out_file, fn)
# Check is the file a MP3 file or not
if not out_file.endswith('.mp3'):
    # File is not a MP3 file, then try to convert it (first rename it)
    dlfn = '.'.join(fn.split('.')[:-1]) + '.' + out_file.split('.')[-1]
    os.rename(fn, dlfn)
    f = AudioFileClip(dlfn)
    f.write_audiofile(fn)
    f.close()
    os.remove(dlfn)

Code is written in Python3. Be sure to install the libraries: python3 -m pip install pytube moviepy MoviePy dont support every audio files, but it support the most of ones: "empty" mp4 (mp4 that only have music), wav, etc...

Why conversion to MP3 is important ? A lot of persons just renames the file, but this cannot convert a file ! If you use VLC by example, VLC will play the file not as an MP3, but as the original format. So, if you play the file with a software that only support MP3, the audio player will return an error.

Tjon answered 30/1, 2023 at 19:19 Comment(1)
Actually, the package moviepy is a "wrapper" for the well-known FFMPEG, but if it is not detected on the current computer, it is automatically downloaded, but not installed as an app or a command. I personnally think it's one of the best way, it's not pure Pythonic but it will work in almost any case. (except on OSes that has no FFMPEG prebuilt binary online)Tjon

© 2022 - 2024 — McMap. All rights reserved.