Getting Youtube Audio Stream with yt_dlp, NOT using pafy

Question:

I have made a GUI youtube audio player.
It uses pafy, a library that gets the stream-urls of a given youtube url.
This is wonderful, but pafy has 2 problems; one is that it, since at least half a year, has an error because it tries to get the dislikes count of youtube (which doesnt work), and it uses youtube_dl library, which doesnt work with about half the videos or so.
My workaround was to change the pafy code a bit, which works great, but it makes it very complicated to share my code with other people. So I need a better workaround. Any tips about this would be greatly appreciated.

What I have in mind, is to just take the bit of code from pafy that is relevant, and put it directly into my code. Problem is, I think that the pafy code is a bit beyond my understanding. One reason is that I don’t know much about object oriented programming, so it’s a bit complicated.

Pafy generally uses youtube_dl, but I found yt_dlp to be a better library. I believe it to be possible to get the audiostreams with yt_dlp, but I dont know how.

The list of audio streams is all I need.

Asked By: Willem van Houten

||

Answers:

Here is a solution that uses yt-dlp. It gets all information about a video and then prints out the url for all available formats. Is this what you are looking for?

import yt_dlp

URL = 'https://www.youtube.com/watch?v=CH50zuS8DD0'

ydl_opts = {}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
    # get all information about the youtube video
    info = ydl.extract_info(URL, download=False)
    
    formats = info['formats']
    print(f"Found {len(formats)} formats")
    # iterate through all of the available formats
    for i,format in enumerate(formats):
        # print the url
        url = format['url']
        print(f"{i}) {url}")
        # each format has many other attributes. You can do print(format.keys()) to see all possibilities

You can take a look at https://github.com/yt-dlp/yt-dlp#embedding-examples for more yt-dlp python examples.

EDIT: need to look at the ‘formats’ section of the returned payload instead of ‘requested_formats’ to actually get all available formats

Answered By: karatekraft
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.