【发布时间】:2020-12-18 04:48:12
【问题描述】:
我在我的一个小型服务器中安装了一个 discord.py 机器人。我已经设置了一个从 YouTube 下载歌曲并将其输出到 VC 的音乐命令。目前,该命令会下载完整的歌曲,对其进行转换,然后然后将其输出到 VC 中,但这个过程非常缓慢。我将如何将音频直接流式传输到 VC?我愿意使用 youtube_dl 代替 pytube3。我不太关心较小的代码优化,因为这只是我和几个朋友的一个小机器人。
感谢您的任何意见!
@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()
【问题讨论】:
标签: python python-3.x discord discord.py python-asyncio