DEV Community

Cover image for Download Youtube video to mp3 with Python

Download Youtube video to mp3 with Python

Stokry on May 17, 2021

I often need to download videos from Youtube in mp3 format. There are many websites where you can convert Youtube videos to mp3, but I am giving y...
Collapse
 
mesuzy profile image
me-suzy

`from pytube import YouTube

def progress(stream, chunk, bytes_remaining):
total_size = stream.filesize
bytes_downloaded = total_size - bytes_remaining
percentage_of_completion = bytes_downloaded / total_size * 100
print(f"Descărcare: {percentage_of_completion:.2f}% completă.")

def download_mp3(video_url, output_path):
yt = YouTube(video_url)
yt.register_on_progress_callback(progress)
audio_stream = yt.streams.filter(only_audio=True).first()
audio_stream.download(output_path)
print(f"Descărcarea melodiei '{yt.title}' este completă.")

video_url = "youtube.com/watch?v=YsmfWkE6FUg"
output_path = "d://Downloads//uuu"
download_mp3(video_url, output_path)
`

Collapse
 
thenetherwatcher profile image
TheNetherWatcher • Edited

Here is a python script through which you can download all the videos in a playlist in .mp3 format

import re
import os
from pytube import Playlist
from pytube import YouTube
from pathlib import Path

YOUTUBE_STREAM_AUDIO = '320' # modify the value to download a different stream
DOWNLOAD_DIR = "./" # directory where you want to store the songs 
AUDIO_DIR = os.path.join(DOWNLOAD_DIR, 'audio')

p = input('Enter the playlist URL(make sure it is a public playlist): ')
playlist = Playlist(p)

# this fixes the empty playlist.videos list
playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")

print(len(playlist.video_urls))

for url in playlist.video_urls:
    yt = YouTube(url)

    video = yt.streams.filter(abr=YOUTUBE_STREAM_AUDIO ).last()
    out_file = video.download(output_path=DOWNLOAD_DIR)
    base, ext = os.path.splitext(out_file)
    new_file = Path(f'{base}.mp3')
    os.rename(out_file, new_file)
    if new_file.exists():
        print(f'{yt.title} has been successfully downloaded.')
    else:
        print(f'ERROR: {yt.title}could not be downloaded!')
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kirbsbtw profile image
Bastian Lipka • Edited

thaks for the post!
i had some problems with the code and i extended it to be able to download single songs and playlists. (sorry for the bad english not nativ)

import youtube_dl

def main():
    link = input("give link: ")
    output = "C:/something/somethin" # example path

    prepLink(link, output)


def downloadVideo(videoInfo ,path):
    try:
        filename = f"{path}/{videoInfo['title']}.mp3"
        options={
            'format':'bestaudio/best',
            'keepvideo':False,
            'outtmpl': filename,
        }
        print(f"[script] downloading {videoInfo['title']}")

        with youtube_dl.YoutubeDL(options) as ydl:
            ydl.download([videoInfo['webpage_url']])
    except:
        print("error occured with one video")

def prepLink(link, path):
    video_url = link
    video_info = youtube_dl.YoutubeDL().extract_info(
        url = video_url,download=False
    )

    try: 
        # trying it for a playlist
        for singleVideoInfo in video_info['entries']:
            downloadVideo(singleVideoInfo, path)
    except KeyError:
        # if the KeyError is raised it will be a  KeyError: 'entries'
        # it is a single video
        downloadVideo(video_info, path)
    print("download complete")

if __name__=='__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

comment for simplification.
You can now also choose the output!

Collapse
 
mortezamsaber profile image
Masih • Edited

Here is also the code to download mp3 from youtube in highest possible quality using pytube:

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!')
Enter fullscreen mode Exit fullscreen mode
Collapse
 
clayhsu profile image
Clay-Hsu

But it I can't edit the mp3 tags of the file download with it. Can anyone tell me what happand?

Collapse
 
rowemore profile image
Rowe Morehouse

why not pytube?

pypi.org/project/pytube/

or pytube3, pytubeX

Collapse
 
chami profile image
Mohammed Chami • Edited

I used the pytube but I don't know how to download files as mp3, I did download the audio only but the format was mp4.
that's why I am trying this library as I found an explanation how to do it.

Collapse
 
mraffi30 profile image
mohammed raffi

Tried this code and, mind full that I am a beginner! Running this in Jupyter Notebook i didn't get prompt to add the URL?

Collapse
 
stokry profile image
Stokry

I will test this out and let you know.

Collapse
 
mraffi30 profile image
mohammed raffi

Thanks....awaiting your feedback.

Collapse
 
bubblicious profile image
bubblicious-a

Thanks. I will try this out.

Collapse
 
stokry profile image
Stokry • Edited

Thank you.

Collapse
 
tankerguy1917 profile image
tankerguy1917

Really cool. I tried it out and it works really fast, and flawlessly.

Collapse
 
stokry profile image
Stokry

Thanks.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Seriously, most of these "How to do X in language Y" type 'articles' should be renamed "How to call a function in language Y"

Collapse
 
stokry profile image
Stokry

Maybe, but I disagree with you.

Collapse
 
langtv profile image
Tran Van Lang

it is really userfully

Collapse
 
stokry profile image
Stokry

Thanks

Collapse
 
mbcrump profile image
Michael Crump

What do I get out of this vs just running the program itself.

Collapse
 
michaelcurrin profile image
Michael Currin • Edited

The CLI might be sufficient for the average use case.

The docs explain how to use the CLI with options.

github.com/ytdl-org/youtube-dl#des...

I guess the downside is that you have to pass those on the command-line each time, so you can write a shell script or Python script which effectively holds all that config logic and asks for user input and runs the library.

The CLI options look comprehensive so I'd guess the features are the same. And for a simple case like download a single video, the CLI way could fit on one or two lines and save having to setup a Python script of 10 or 20 lines.

But maybe using the library in a Python script helps for a level of abstraction. Like if you want to build a web or GUI interface on top or have more control on what to download and where it is saved and making directories or printing a progress report or retrying bad URLs etc.

Collapse
 
langtv profile image
Tran Van Lang

Help me how to convert and download to mp4 file.

Collapse
 
stokry profile image
Stokry

You can use pytube. It's lightweight, dependency-free Python library (and command-line utility) for downloading YouTube Videos.

Collapse
 
tebrizetayi profile image
Tabriz

Here is a list of top YouTube to MP3 converters:

Collapse
 
zeppipoju1 profile image
zeppipoju*

hi, where does the file go after you download it? it isnt showing up for me anywhere

Collapse
 
pablo_gnas profile image
Pablo

I've got "WARNING: yaBcFvKEXDo" and it suggested me to install ffmpeg or avconv to fix this, but what should I do when I install it?