11

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.

scrpy
  • 809
  • 4
  • 22
Muhammad Khan
  • 687
  • 1
  • 9
  • 25

8 Answers8

8

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)

scrpy
  • 809
  • 4
  • 22
  • Thanks, but how can I do this in Python (3.4)? – Muhammad Khan Dec 12 '17 at 12:42
  • 1
    Is it possible to pipe audio from pytube to ffmpeg so downloading and conversion could happen in parallel? – ritiek Mar 20 '20 at 09:24
  • 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. – scrpy Mar 20 '20 at 16:18
  • 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 https://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. – ritiek Mar 23 '20 at 12:37
  • 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... – scrpy Mar 24 '20 at 15:51
  • 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. – ritiek Mar 28 '20 at 20:38
  • @CrazyVideoGamez Have you tried? Did it work? AFAIK it won't work, see my comment on [this answer](https://stackoverflow.com/a/57264246/8951763) below – scrpy May 04 '21 at 16:51
  • @scrpy I have tried, and the browser displayed correctly as an audio file – CrazyVideoGamez May 04 '21 at 23:26
3

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.

scrpy
  • 809
  • 4
  • 22
TheoNeUpKID
  • 490
  • 3
  • 9
  • 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. – scrpy Aug 05 '19 at 16:53
  • 1
    It's YouTube, not Youtube – CrazyVideoGamez Feb 26 '21 at 16:11
1

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

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()
Mohnish
  • 1,026
  • 1
  • 10
  • 16
SOM Tube
  • 11
  • 2
0

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.

scrpy
  • 809
  • 4
  • 22
0
from pytube import YouTube

yt = YouTube(url)

yt.streams.get_audio_only().download(output_path='/home/',filename=yt.title)
Syscall
  • 16,959
  • 9
  • 22
  • 41
0

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")
Tomerikoo
  • 12,112
  • 9
  • 27
  • 37
0

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.