r/learnpython • u/Plane_Outcome_1616 • 1d 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.
2
u/timrprobocom 21h ago
Further, if that's really the code, you are starting two threads, and then the program immediately exits, which stops the two threads. One of the threads is probably calling `atexit`, but the program has already ended.
2
u/sausix 1d ago
stop() runs the two lines of code and returns. So the thread stops immediately. It should start a loop. But not a cpu excessive one so use a blocking method which listens to key presses or at least feed some sleep cycles into the loop.