Playing music with a bot from Youtube without downloading the file

后端 未结 1 824
半阙折子戏
半阙折子戏 2020-12-19 19:46

How would i go about playing music using a discord bot from Youtube without downloading the song as a file?

I\'ve already had a look at the included music bot in the

相关标签:
1条回答
  • 2020-12-19 19:58

    To play music without downloading it, simply use this code into your play function :

    ydl_opts = {'format': 'bestaudio'}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(video_link, download=False)
        URL = info['formats'][0]['url']
    voice = get(self.bot.voice_clients, guild=ctx.guild)
    voice.play(discord.FFmpegPCMAudio(URL))
    

    Here is what each line is used for :

    • ydl_opts = {'format': 'bestaudio'} : get the best possible audio
    • with youtube_dl.YoutubeDL(ydl_opts) as ydl: : initialize youtube-dl
    • info = ydl.extract_info(video_link, download=False) : get a dictionary, named info, containing all the video information (title, duration, uploader, description, ...)
    • URL = info['formats'][0]['url'] : get the URL which leads to the audio file of the video
    • voice = get(self.bot.voice_clients, guild=ctx.guild) : initialize a new audio player
    • voice.play(discord.FFmpegPCMAudio(URL)) : play the right music


    However, Playing audio from an URL without downloading it causes a known issue explained here
    To fix it, just add a variable, for instance, FFMPEG_OPTIONS which will contain options for FFMPEG:

    FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    

    Once you've created the variable, you just have to add one argument to the FFmpegPCMAudio method:

    voice.play(discord.FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
    
    0 讨论(0)
提交回复
热议问题