我正在制作一个机器人,并且我已经弄清楚如何让它播放来自 youtube 的音频.音频是流式传输的,因此文件不会下载到我的 PC 上.这是我的代码:
I have a bot I am producing and I have figured out how to make it play audio from youtube. The audio is streamed so the files are not downloaded to my PC. Here is my code:
@bot.command(name='play', aliases=['p'], help='Plays a song.')
async def play(ctx, url):
channel = ctx.message.author.voice.channel
if ctx.guild.voice_client is None:
await channel.connect()
client = ctx.guild.voice_client
player = await YTDLSource.from_url(url, stream = True)
ctx.voice_client.play(player)
await ctx.send('Now Playing: {}'.format(player.title))
我正在使用此块中未显示的一些代码,因为它是 basic_voice.py 包的一部分(可在此处找到:https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py,我使用的是第 12-52 行).我的问题是音频在最后被切断,FFMPEG 窗口在我的电脑上关闭.当我在我的 PC 上测试本地文件时也发生了这种情况.我不确定为什么 FFMPEG 会提前关闭,但如果可能的话,我想修复它.此外,如果它很重要,最后切断的量取决于正在播放的音频的长度.播放器工作时没有延迟,只是莫名其妙地停止了.
I am using some code that is not shown in this block because it is part of the basic_voice.py package (found here: https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py, I am using lines 12-52). My issue is that the audio is cut off at the end, with the FFMPEG window closing on my PC. This happened when I tested local files on my PC as well. I am not sure why FFMPEG just closes early, but I'd like a fix to it if possible. Also, if it's important, the amount cut off at the end is dependant on the length of the audio being played. The player works with no lag, it just mysteriously stops.
这是一个已知问题,当您尝试制作一个不下载它正在播放的歌曲的机器人时.这里解释:https://support.discord.com/hc/en-us/articles/360035010351--Known-Issue-Music-Bots-Not-Playing-Music-From-Certain-Sources一个>
This is a known issue when you try to make a bot which doesn't download the song it's playing. It is explained here : https://support.discord.com/hc/en-us/articles/360035010351--Known-Issue-Music-Bots-Not-Playing-Music-From-Certain-Sources
要解决此问题,您可以使用 discord.py 中的 FFmpegPCMAudio
方法并提供特定选项,以便机器人能够重新连接并继续播放视频:
To solve the problem, you can use the FFmpegPCMAudio
method from discord.py and give specific options so the bot will be able to reconnect and continue to play the video :
ydl_opts = {'format': 'bestaudio'}
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
@bot.command(name='play', aliases=['p'], help='Plays a song.')
async def play(ctx, url):
channel = ctx.message.author.voice.channel
voice = get(self.bot.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
source = ydl.extract_info(url, download=False)['formats'][0]['url']
voice.play(discord.FFmpegPCMAudio(song['source'], **FFMPEG_OPTIONS))
voice.is_playing
这篇关于播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!