2016-12-28 34 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