本文介绍了使用python子进程和线程播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试打开警报,然后循环播放声音,直到警报关闭.然后声音应该停止了.
I am trying to open an alert, then loop a sound until the alert is closed. Then the sound should stop.
我尝试过:
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()
但是由于某种原因,声音甚至无法播放.
But for some reason the sound doesn't even play.
推荐答案
这是因为process.poll()
在处理完成后返回0
,这是一个虚假的值.
It's because process.poll()
returns 0
after the process finishes, which is a falsy value.
快速修复:
while not stop_sound:
if process.poll() is not None:
break
这篇关于使用python子进程和线程播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!