問題描述
我正在制作一個機器人,并且我已經弄清楚如何讓它播放來自 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模板網!