2016-12-28 37 views
0

我试图打开警报,然后循环播放声音,直到警报关闭。然后声音应该停止。使用python子进程和线程播放声音

我尝试这样做:

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

但由于某些原因的声音不连戏。

回答

1

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

快速修复:

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