在while循环中异步播放声音



如何在while循环中异步播放声音,但不要重叠声音。等待上一次播放结束,然后再播放一次,以此类推,直到while循环运行为止。当然,while循环应该在播放过程中继续运行。

import time
from playsound import playsound
while True:
time.sleep(0.1)
playsound('sound.wav', block=False)  # Please suggest another module, "playsound" stopped working and I gave up on fixing it.
print('proof that the while loop is running while the sound is playing')

编辑:还有一件事,播放不应该排队,一旦while循环停止,播放也必须停止(只让播放的一个播放完(

第二天我设法解决了这个问题。

我使用线程,我必须在类中使用它来检查它是否有效,因为我不能只使用t1=线程。while循环中的线程(target=func(t1.start((,因为我之前需要检查该线程是否处于活动状态。

所以。。。

import threading
from playsound import playsound

class MyClass(object):
def __init__(self):
self.t1 = threading.Thread(target=play_my_sound)

def play_my_sound():
playsound('sound.wav')

def loop():
while True:
if not my_class.t1.is_alive():
my_class.t1 = threading.Thread(target=play_my_sound)
my_class.t1.start()

if __name__ == "__main__":
my_class = MyClass()
loop()

这回答了我的问题,在while循环中,声音在它自己的线程上播放,只有在前一个线程完成后才开始播放。

注意:我对playsound库有问题,但这是因为我必须使用\而不是/作为路径——在我的原始代码中,声音与主脚本不在同一文件夹中。我还不得不降级到playsound==1.2.2版本。

最新更新