我正在尝试打开警报,然后循环播放声音直到警报关闭。然后声音应该停止。
我试过了:
import threading
import time
import subprocess
stop_sound = False
def play_alarm(file_name = "beep.wav"):
"""Repeat the sound specified to mimic an alarm."""
while not stop_sound:
process = subprocess.Popen(["afplay", file_name], shell=False)
while not stop_sound:
if process.poll():
break
time.sleep(0.1)
if stop_sound:
process.kill()
def alert_after_timeout(timeout, message):
"""After timeout seconds, show an alert and play the alarm sound."""
global stop_sound
time.sleep(timeout)
process = None
thread = threading.Thread(target=play_alarm)
thread.start()
# show_alert is synchronous, it blocks until alert is closed
show_alert(message)
stop_sound = True
thread.join()
但由于某些原因,声音甚至没有播放。
答案 0 :(得分:1)
这是因为process.poll()
在流程完成后返回0
,这是一个假值。
快速修复:
while not stop_sound:
if process.poll() is not None:
break