Playing a queue of audio tracks in discord.py(在 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
这篇关于在 discord.py 中播放音轨队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 discord.py 中播放音轨队列


基础教程推荐
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01