I have a discord.py bot setup in a small server of mine. I have setup a music command that downloads a song from YouTube and outputs it into a VC. At the moment, the command downloads the full song, converts it, and then outputs it into a VC, but this process is heavily slow. How would I go about streaming the audio directly into the VC? I'm open to use youtube_dl in place of pytube3. I don't care much about smaller code optimizations as this is just a small bot for a few friends and me.
Thanks for any input!
@bot.command()
async def play(ctx, *song):
if ctx.author.voice is None or ctx.author.voice.channel is None:
await ctx.send("You aren't in a VC!")
return
print(song) #debugging
os.system("rm music.mp3")
ydl_opts = {
'noplaylist': True,
'outtmpl': 'music',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '128',
}],
'format': '139',
}
youtube = pytube.YouTube(str(song).strip("(,)'"))
video = youtube.streams.filter(only_audio=True).first()
await ctx.send("downloading")
video.download(filename="music")
await ctx.send("converting...")
os.system("ffmpeg -i music.mp4 -map 0:a:0 -b:a 96k music.mp3")
voice_channel = ctx.author.voice.channel
vc = await voice_channel.connect()
vc.play(discord.FFmpegPCMAudio('music.mp3'), after=lambda e: print('done', e))
while vc.is_playing():
await asyncio.sleep(1)
await ctx.voice_client.disconnect()