Discord.py 循环音频源

问题描述

有谁知道如何在 FFmpeg 中循环相同的源代码

这是我的代码

@bot.command(pass_context = True)
async def join(ctx):

if (ctx.author.voice):
    channel = ctx.message.author.voice.channel
    voice = await channel.connect()
    source = FFmpegPCMAudio('test.mp3')
    player = voice.play(source)
else:
    await ctx.send('You need to be in a Voice-Channel.')

我希望永久循环播放音频文件“test.mp3”。我在互联网上搜索过,但那里给出的所有结果都已过时。

解决方法

这是一种知道歌曲何时播放完毕的方法。

if (ctx.author.voice):
    finished = False 
    channel = ctx.message.author.voice.channel
    voice = await channel.connect()

    voice.play(discord.FFmpegPCMAudio("song.mp3"),after=lambda e: finished = True)

使用 lambda 函数,您可以实现循环结构以在完成后重播歌曲。

,

这是我目前为自己使用的解决方案:

async def play_source(voice_client):
    source = FFmpegPCMAudio("test.mp3")
    voice_client.play(source,after=lambda e: print('Player error: %s' % e) if e else bot.loop.create_task(play_source(voice_client)))

这个解决方案只是一个基本的解决方案。源完成后,再次以相同的 voice_client 启动。

如果音频一开始就开始加速,那么只需在源和 voice_client.play 之间放置一个 await asyncio.sleep(0.5)

首先,只需像这样替换您的代码:

@bot.command(pass_context = True)
async def join(ctx):

if (ctx.author.voice):
    channel = ctx.message.author.voice.channel
    voice = await channel.connect()
    bot.loop.create_task(play_source(voice))
else:
    await ctx.send('You need to be in a Voice-Channel.')