【问题标题】:How to make a discord bot loop audio? [discord.py]如何制作不和谐的机器人循环音频? [不和谐.py]
【发布时间】:2020-10-08 23:22:41
【问题描述】:

我想让机器人播放一段音频,当音频结束时,它会重播音频。

我有什么:

@client.command()
async def play(ctx):
await ctx.channel.purge(limit=1)
channel = ctx.author.voice.channel
if channel:
    print(channel.id)
    await channel.connect()
guild = ctx.guild
audio_source = discord.FFmpegPCMAudio('audio.mp3')
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild=guild)
if not voice_client.is_playing():
    voice_client.play(audio_source, after=None)

【问题讨论】:

    标签: python discord discord.py discord.py-rewrite


    【解决方案1】:

    discord.VoiceClient.Play() 有一个after 参数,在音频流结束时调用该参数。通常,它应该用于显示错误消息,但您可以使用它来重复歌曲,如下所示:

    @client.command()
    async def play(ctx):
        await ctx.channel.purge(limit=1)
        channel = ctx.author.voice.channel
        voice = get(self.bot.voice_clients, guild=ctx.guild)
    
        def repeat(guild, voice, audio):
            voice.play(audio, after=lambda e: repeat(guild, voice, audio))
            voice.is_playing()
    
        if channel and not voice.is_playing():
            audio = discord.FFmpegPCMAudio('audio.mp3')
            voice.play(audio, after=lambda e: repeat(ctx.guild, voice, audio))
            voice.is_playing()
    

    【讨论】:

    • 方法repeat() 调用自身。这不会导致堆栈随着每次调用而增长的无限递归。这是一个好方法吗?有没有什么可以以迭代的方式做同样的事情?
    • 如果你不希望它是无限的,你只需要在repeat函数中删除after=lambda e: repeat(ctx)。他想在完成后再次播放音频,所以这就是我将其设为无限的原因
    • 我试过使用 after,虽然没有 lambda。但是我注意到这首歌的第一个实例只有在 after method 完成运行后才开始播放。我的印象是当前歌曲播放完毕后会调用after method
    • 这就是 after 参数的作用。它需要一个可调用的值,当视频结束时会调用这个值。
    • 但在我所有的测试中,after method 对我来说并不等待歌曲完成。相反,它会在歌曲开始之前执行
    猜你喜欢
    • 2021-09-30
    • 2020-06-20
    • 2021-07-07
    • 1970-01-01
    • 2019-04-04
    • 2019-12-08
    • 2018-08-24
    • 2021-09-26
    • 2018-03-20
    相关资源
    最近更新 更多