gpt4 book ai didi

python - 使用python子进程和线程播放声音

转载 作者:行者123 更新时间:2023-12-03 00:36:01 25 4
gpt4 key购买 nike

我试图打开警报,然后循环播放声音,直到警报关闭。然后声音应停止。

我尝试了这个:

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()

但是由于某种原因,声音甚至无法播放。

最佳答案

这是因为process.poll()在过程完成后返回0,这是一个虚假的值。

快速解决:

while not stop_sound:
if process.poll() is not None:
break

关于python - 使用python子进程和线程播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41369145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com