Is there a way to directly stream audio from a youtube video using youtube-dl or pafy library in python 3.7?
Asked Answered
L

1

6

Instead of again and again downloading the audio from a youtube video, I want to stream the audio and directly access the raw audio bytes from the buffer. In other words, I want to store the raw audio bytes in RAM and use them in my python script without the need of fully downloading and saving the audio file on the system in order to cut down on the memory write cycles. Is there any workaround in youtube-dl library or pafy library to do the same?

Lumbricoid answered 18/3, 2020 at 17:53 Comment(0)
E
5

Yes, there is, I just found out how it works. In rewrite, you can use discord.FFmpegPCMAudio(url) to do that. You have to keep in mind that the url you put into discord.FFmpegPCMAudio() isn't the YouTube link you can copy from the browser, for example https://www.youtube.com/watch?v=videoid. You get a huge json dictionary, in which the "real" url is in, from this code:

# Get a json library with general video information, as well as the url we need to stream the audio.

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
     song_info = ydl.extract_info("https://www.youtube.com/watch?v=INPUTYTLINKHERE", download=False)

If you want, you can print out song_info to see some more information about the video, like the amount of views, likes, and more:

print(song_info)

And here is the final code: (I use @client and async def on_message(message))

# The "real" url is in song_info["formats"][0]["url].

message.guild.voice_client.play(discord.FFmpegPCMAudio(song_info["formats"][0]["url"]))
message.guild.voice_client.source = discord.PCMVolumeTransformer(message.guild.voice_client.source)
message.guild.voice_client.source.volume = 1

I hope this made it clear.

Elixir answered 24/3, 2020 at 13:43 Comment(1)
Is there any non discord way. I wanna make a web all not a discord botLaudable

© 2022 - 2024 — McMap. All rights reserved.