在 discord.py 中播放音轨队列

2022-01-15 00:00:00 python discord.py

问题描述

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

So I am making this music discord bot on discord.py. This bot just plays a playlist from local mp3 files on my computer. So I have a function that plays the queue and it goes like this:

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 中发送消息并执行其他操作.我面临的问题是这一行的结果:

And I want to convert this function to an async function because I want to be able to send messages and do other things in discord.py inside this function. The problem I'm facing is a result of this line:

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

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

If I make this function an async function than I'll have to put an await statement, and If I do that it will be like this:

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

问题在于它给了我错误:在异步函数之外等待"所以我也尝试使用 asyncio.run(),然后在第一首歌之后它给了我一个巨大的错误滚动,接下来我该怎么办?

The problem with that is that it's giving me the error: "await outside of async function" So I also tried using asyncio.run(), and then after the first song it's giving me a huge scroll of errors, What do I do next?


解决方案

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

I have found an answer to my own question. The answer is to use asyncio.Event() I did it like this:

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

相关文章