我正在播放音频,同时从键盘输入。我使用线程来实现这一目标。我创建了一个新线程来运行音频,并从主线程中听取输入。但我希望根据键盘的某些输入停止播放音频。
因为我不能"杀死"来自另一个线程的线程,我不能让音频线程听取主线程,除非它已经停止播放音频,我该如何实现呢?
编辑: 我写了这段代码:
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
为什么会这样?此外,即使在第二次循环迭代之后,进程终止(p.is_alive()返回false)但音频仍在继续播放。音频不会停止。
答案 0 :(得分: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()