0

对于我的应用程序,我使用 tkinter 并从 API 播放声音。

我线程我的“test_tts”函数,以便 Tkinter UI 不会崩溃。

问题之一是,如果您想停止/跳过声音,则不能,因为winsound.PlaySound(None, winsound.SND_ASYNC)在另一个线程中执行时不起作用(这是有道理的)。

有什么办法可以阻止 winsound 在另一个线程中发生?或者,有没有办法完全停止线程?

def test_tts():
    message = entry_1.get()

    messages = message.split("||")
    q = queue.Queue()

    voice_files = []

    for message in messages:
        if message[0] == " ":
            message = message[1:]
        elif message == ",":
            continue

        print(message.split(": "))

        voice = message.split(": ")[0]
        voice = voice.lower()
        print(voice)
        text = message.split(": ")[1]
        print(text)

                    date_string = datetime.now().strftime("%d%m%Y%H%M%S")
                    urllib.request.urlretrieve( #Gets this from an API request that was removed from this code snippet
                        ud_ai.json()["path"], f"AI_voice_{date_string}.wav"
                    )
                    time.sleep(1)
               
                    voice_files.append(f"AI_voice_{date_string}.wav")
                    time.sleep(1)

                    waitingToProcess = False

    def thread_function():
        while True:
            sound = q.get()
            if sound is None:
                break
            winsound.PlaySound(sound, winsound.SND_FILENAME)
            os.remove(sound)

    if __name__ == "__main__":
        t = threading.Thread(target=thread_function)
        t.start()
        for voice_file in voice_files:
            q.put(voice_file)
            time.sleep(1)
        t.join()


def skip_tts(self):
    print("Skipping TTS")
    winsound.PlaySound(None, winsound.SND_ASYNC)

button_1.bind("<Button-1>", skip_tts)

button_2.bind("<Button-1>", lambda x: threading.Thread(target=test_tts).start())

window.mainloop()

# There was lots of code cut from this snippet, if you'd like to see a full snippet go here: 
https://gist.github.com/mmattbtw/9c09c1d3ff2c447229314b69a8919e48

4

0 回答 0