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