0

나는 오디오를 재생 중이고 동시에 키보드에서 입력을 받는다. 나는 이것을 달성하기 위해 스레딩을 사용했다. 내가 오디오를 실행하고 메인 스레드에서 입력을 듣고 새 스레드를 만들었습니다. 하지만 키보드의 특정 입력을 기반으로 오디오 재생을 중지하고 싶습니다.파이썬에서 조건에 따라 오디오 재생을 중지하는 방법은 무엇입니까?

다른 스레드에서 스레드를 "종료"할 수 없기 때문에 오디오 재생이 중지되지 않은 한 오디오 스레드가 기본 스레드를 수신 대기 할 수 없으므로 어떻게해야합니까?

편집

: 이 나는이 코드를 작성했습니다 :

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

왜 이런 일이 :

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

이 출력은? 또한 두 번째 루프 반복 후에도 프로세스가 종료되고 (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