我在播放音频,同时从键盘上获取输入。我已经使用线程来实现这一目标。我创建了一个新线程来运行音频,并聆听主线程的输入。但是我想根据键盘的某些输入来阻止音频播放。
由于我无法从另一个线程"杀死"线程,而且我不能让音频线程收听主线程,除非它停止播放音频,否则我该如何实现?
编辑:我写了此代码:
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),但音频仍在播放。音频不会停止。
解决此问题的解决方案是两个线程之间具有公共变量/标志。该变量会发出音频播放线程的信号,以结束或等待更改。
这是一个相同的示例。
在这种情况下,线程将在获取信号时退出。
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 Stopn'))
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()