Search code examples
pythonpython-3.xyoutubemp3youtube-dl

How to get the direct link to a youtube video in the mp3 format in Python?


I am currently trying to find out how to get the direct link to the youtube video in mp3 format without downloading it on a computer, so I just need to get the link leading to the internet mp3 file. I tried to do it by the youtube_dl library in Python.

My code:

import youtube_dl
link = 'https://www.youtube.com/watch?v=8fATAQtY9ag'

ydl_opts = {
    'format': 'bestaudio'
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    info = ydl.extract_info(link, download=False)
    print(info['formats'][0]['url'])

I am getting the result:

[youtube] 8fATAQtY9ag: Downloading webpage

https://rr4---sn-gvnuxaxjvh-n8ves.googlevideo.com/videoplayback?expire=1667397364&ei=lCJiY6fjI7P97QSmxK_QCA&ip=95.72.245.107&id=o-AFd3ju7rPL4AbxE5TTqyDlwEVYa3O038Ljvp4iTFz594&itag=249&source=youtube&requiressl=yes&mh=6d&mm=31%2C29&mn=sn-gvnuxaxjvh-n8ves%2Csn-gvnuxaxjvh-n8vk&ms=au%2Crdu&mv=m&mvi=4&pl=22&gcr=ru&initcwndbps=1213750&vprv=1&mime=audio%2Fwebm&ns=BRs0-MEqtt1vrCzmr61YjwoI&gir=yes&clen=1668462&dur=253.441&lmt=1614142570111218&mt=1667375377&fvip=8&keepalive=yes&fexp=24001373%2C24007246&c=WEB&txp=1311222&n=c2zXxbznF8OLQmMbvo&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cgcr%2Cvprv%2Cmime%2Cns%2Cgir%2Cclen%2Cdur%2Clmt&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AG3C_xAwRgIhAPWkeRlVf2AmqbDFXrRJSLT0IMcLmlU4pQoMty5b7zzDAiEAw50GzyfT6NucOra_4kJ2BYfoPtWEa5lOCtQEcuF-Ekw%3D&sig=AOq0QJ8wRAIgFP0t2TNC_rvUpjX3Q6DqExtm0pQ5gSlYlpq_4iCv2r8CIFwzl_uW5aQ1knRCDfoVD9eVF4By4qaCBCEsZZKyPBba

This long link contains an audio file with the weba extension, but not the mp3 one. So, may be there is a way to solve this problem using this or any other library?


Solution

  • YouTube has never had audio-only video formats with MP3 audio, and haven't had mixed (audio+video) formats with MP3 audio for years.

    Your options are:

    1. Not use mp3. An obvious one, but pretty much anything supports mp4a these days, and lots support opus. (If you plan to use it in a browser, here are the stats for browser support for AAC and opus, and MP3 for comparison)
    2. If you do specifically need mp3, download and convert another audio-only format (currently, the choice is between mp4a or opus). This is available in youtube-dl/yt-dlp if you have ffmpeg installed, enabled with the following options (remember to also set format together with them):
    {
        'extractaudio': True,
        'audioformat': 'mp3',
    }
    

    Also, I think a useful information here: YouTube puts the IP address of the video requester inside the URL video, and on some videos makes it a part of the signature that authenticates you - when that's the case, the video has to be downloaded from the same IP address.