音频完成后如何结束 AudioPlayer 播放器

How to end AudioPlayer player when audio is done

如何检测音频播放完毕后调用 AudioPlayer.stop() 以便可以在 python AudioPlayer 库中再次播放?

我的解决方案是检查音频的长度,然后使用线程库的 wait 函数等待歌曲结束。绝对不是最有效的选择,但我是这样做的:

from audioplayer import AudioPlayer
from mutagen.mp3 import MP3
import threading
import random
import os


event = threading.Event()
funcAplayer = AudioPlayer('Audio/'+(random.choice(os.listdir('Audio/'))))


def function_a():  # A
    funcAplayer.play(loop=False, block=False)
    audio = MP3(funcAplayer.filename)
    event.wait(int(audio.info.length + 0.05))
    funcAplayer.stop()

我在末尾添加了几分之一秒,以便有轻微的延迟,从而减少垃圾邮件的垃圾邮件,但这不是必需的。

您只需将 block 参数设置为 True,这样 play 函数将 return 播放完成后(如 documentation 所述)