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
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 audiowith youtube_dl.YoutubeDL(ydl_opts) as ydl:
: initialize youtube-dlinfo = 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 videovoice = get(self.bot.voice_clients, guild=ctx.guild)
: initialize a new audio playervoice.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))