【问题标题】:Playing a queue of audio tracks in discord.py在 discord.py 中播放音轨队列
【发布时间】:2020-12-18 21:55:55
【问题描述】:

所以我在 discord.py 上制作了这个音乐不和谐机器人。 这个机器人只是从我电脑上的本地 mp3 文件中播放一个播放列表。 所以我有一个播放队列的函数,它是这样的:

def play_song(ctx, voice):
    if len(queue) == 0:
        print('All the songs have been played')
        create_queue()
        return

    song_ = queue[0][len('songs/'):-16]
    voice.play(discord.FFmpegPCMAudio(queue[0]), after=lambda e: play_song(ctx, voice))
    print(f'Now playing {song_}')
    del queue[0]

我想将此函数转换为异步函数,因为我希望能够在此函数内部的 discord.py 中发送消息并执行其他操作。 我面临的问题是这一行的结果:

voice.play(discord.FFmpegPCMAudio(queue[0]), after=lambda e: play_song(ctx, voice))

如果我让这个函数成为一个异步函数,那么我将不得不添加一个 await 语句,如果我这样做,它将是这样的:

voice.play(discord.FFmpegPCMAudio(queue[0]), after=lambda e: await play_song(ctx, voice))

问题在于它给了我错误: "await outside of async function" 所以我也尝试使用asyncio.run(),然后在第一首歌之后它给了我一个巨大的错误滚动,接下来我该怎么办?

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    尝试在顶部使用async def play_song(ctx, voice):。您不能在非async 函数中使用await

    【讨论】:

    • await outside async function 错误发生在函数异步时,如果不是我不需要等待,我认为这是因为函数 after 是非异步的
    • await 在你的 lambda 函数中,它不是 async
    【解决方案2】:

    我找到了自己问题的答案。 答案是使用asyncio.Event() 我是这样做的:

    async def play_song(ctx, voice):
        global stop_playing, pos_in_q, time_from_song
        event = asyncio.Event()
        event.set()
        while True:
            await event.wait()
            event.clear()
            if len(queue) == pos_in_q - 1:
                await ctx.send('Party is over! use the `.arse-play` to play again.')
                print('Party is over!')
                create_queue()
                break
            if stop_playing is True:
                stop_playing = False
                break
    
            song_ = queue[pos_in_q][len('songs/'):]
            voice.play(discord.FFmpegPCMAudio(queue[pos_in_q]), after=lambda e: event.set())
            print(f'Now playing {song_}')
            time_from_song = time.time()
            pos_in_q += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      相关资源
      最近更新 更多