繁体   English   中英

如何根据Python中的条件停止播放音频?

[英]How to stop an audio from playing based on condition in Python?

我正在播放音频,并同时从键盘进行输入。 我已经使用线程来实现这一点。 我创建了一个新线程来运行音频,并侦听主线程的输入。 但是我想根据键盘的某些输入来停止播放音频。

由于我无法“杀死”另一个线程中的一个线程,并且除非音频线程停止播放音频,否则我无法使音频线程监听主线程,我该如何实现呢?

编辑:我编写此代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM