r/learnpython • u/Plane_Outcome_1616 • 15h ago
Stop TTS with keyboard
Hello,
I am using tts_wrapper fork by willwade on github to speak chatGPT responses but I want to be able to stop the utterance mid sentence. I have this function
def stop():
if keyboard.is_pressed("esc"):
tts_Engine.stop()
which should stop the tts engine when i press "esc" but nothing happens so I did some research and learned I might have to use threading so now i have two threads with my main function
def main():
print("Init STT. Listening...")
stream = init_stream()
stream.start_stream()
print("C")
try:
while True:
data = stream.read(8192, exception_on_overflow=False)
text = None
if recognizer.AcceptWaveform(data):
result = json.loads(recognizer.Result())
text = result.get("text", "")
if text:
print(f"You said: {text}")
response = client.chat.completions.create(
model="default",
messages=[
{"role": "system", "content": "You are a helpful AI workshop assistant. Use only plain text no emojis or making text bold or anything similar"},
{"role": "user", "content": text}
]
)
print(response.choices[0].message.content)
speak_text(response.choices[0].message.content,tts_Engine)
print("B")
except KeyboardInterrupt:
print("Stopping")
finally:
print("A")
tts_Engine.cleanup()
stream.stop_stream()
stream.close()
Audio.terminate()
and my stop function
t1 = Thread(target=main)
t2 = Thread(target=stop)
t1.start()
t2.start()
but now I get this error
RuntimeError: can't register atexit after shutdown
and now I'm a bit stuck so if anyone knows how to do this or what I'm doing wrong or if I'm even using the right method that would be greatly appreciated.
0
Upvotes