'I'm having an issue with my discord bot playing audio from a youtube url

sync def hog():
channel = bot.get_channel(964971002289356893)
url = 'https://www.youtube.com/watch?v=GyRmkAfpCOM'
await asyncio.sleep(1)
voice_channel = bot.get_channel(int(964971002289356893))
vc = await voice_channel.connect()
#vc.play(discord.FFmpegPCMAudio('C:/Users/alexa/Downloads/hogrider.mp3'))
vc.play(discord.FFmpegPCMAudio(source='https://www.youtube.com/watch?v=GyRmkAfpCOM', executable='ffmpeg.exe'))
while vc.is_playing():
    await asyncio.sleep(5)
await vc.disconnect()

It works fine with the audio file from my laptop, but I want to play it from a youtube link. It gives me an error: https://www.youtube.com/watch?v=GyRmkAfpCOM: Invalid data found when processing input

Thank you in advance



Solution 1:[1]

Maybe you should change your code to this, but make sure you need to install ffmpeg. I'm using this code for my music player (on my discord bot)

async def hog(ctx, url:str):
   channel = bot.get_channel(put your channel here)
   vc = ctx,.voice_client
   await asyncio.sleep(1)
   video = search(query=title)
   source = video['formats'][0]['url']
   vc.play(FFmpegPCMAudio(source, **FFMPEG_OPTIONS))

as you can see there is search function being called.

def search(query):
YDL_OPTION = {
    'format': 'bestaudio/best',
    'noplaylist': True,
    'nocheckcertificate': True,
    'default_search': 'auto',
    'geo_bypass': True,
}

with YoutubeDL(YDL_OPTION) as ydl:
    try:
        requests.get(query)
    except:
        info = ydl.extract_info(f"ytsearch:{query}", download=False)['entries'][0]
    else:
        info = ydl.extract_info(query, download=False)
return info

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MorpKnight