0

私はオーディオを再生しており、同時にキーボードから入力しています。私はこれを達成するためにスレッドを使用しています。私は、オーディオを実行し、メインスレッドからの入力を聞く新しいスレッドを作成しました。しかし、私は、キーボードからの特定の入力に基づいて、オーディオの再生を停止したい。Pythonの条件に基づいてオーディオの再生を停止する方法は?

スレッドを別のスレッドから「強制終了」できず、オーディオの再生を停止していない限り、オーディオスレッドをメインスレッドにリッスンさせることはできません。どうすれば達成できますか?

EDIT: 私はこのコードを書いた:

from multiprocessing import Process 
import os 

p = Process(target=os.system, args=("aplay path/to/audio/file",)) 
p.start()                             
print("started")                
while p.is_alive(): 
    print("inside loop") 
    inp = input("give input") 
    if inp is not None: 
     p.terminate() 
     print(p.is_alive())  # Returns True for the first time, False for the second time 
     print("terminated") 

これが出力されます:

started 
inside loop 
give input2 
True 
terminated 
inside loop 
give input4 
False 
terminated 

ですが、なぜでしょうか?また、2回目のループの繰り返しの後でも、プロセスは終了します(p.is_alive()はfalseを返します)が、オーディオは再生を続けます。音声は止まらない。

答えて

0

この問題の解決策は、両方のスレッド間に共通の変数/フラグを設定することです。この変数は、オーディオ再生スレッドに終了を知らせるか、または変更を待つ。

これは同じ例です。

この場合、信号を受信するとスレッドが終了します。

import time 
import winsound 
import threading 

class Player(): 
    def __init__(self, **kwargs): 
     # Shared Variable. 
     self.status = {} 
     self.play = True 
     self.thread_kill = False 
    def start_sound(self): 
     while True and not self.thread_kill: 
      # Do somthing only if flag is true 
      if self.play == True: 
       #Code to do continue doing what you want. 


    def stop_sound(self): 
     # Update the variable to stop the sound 
     self.play = False 
     # Code to keep track of saving current status 

    #Function to run your start_alarm on a different thread 
    def start_thread(self): 
     #Set Alarm_Status to true so that the thread plays the sound 
     self.play = True 
     t1 = threading.Thread(target=self.start_sound) 
     t1.start() 

    def run(self): 
     while True: 
      user_in = str(raw_input('q: to quit,p: to play,s: to Stop\n')) 
      if user_in == "q": 
       #Signal the thread to end. Else we ll be stuck in for infinite time. 
       self.thread_kill = True 
       break 
      elif user_in == "p": 
       self.start_thread() 
      elif user_in == "s": 
       self.stop_sound() 
      else: 
       print("Incorrect Key") 

if __name__ == '__main__': 
    Player().run() 
+0

私はループ内でオーディオファイルを再生しようとしていません。それは私が中断する必要がある長いオーディオファイルの一つです。この行 'while self.alarm_status == True:winsound.PlaySound(" alarm.wav "、winsound.SND_FILENAME)'は、オーディオファイルがループで再生されているときにのみ動作します。各フル再生後にのみ条件を確認することができます。オーディオファイルを再生する間の状態をチェックしません。 – anomaly

+0

私の編集をご覧ください。私はマルチプロセッシングを使用しました。 – anomaly

+0

私は自分の答えを編集して他のスレッドで作業を続けますが、オーディオを一時停止するには、自分でファイルをデコードしてストリームするか、そのようなライブラリを使用するか、ほとんどの場合、再生は一時停止をサポートしていません)。 – CodeCollector

関連する問題