I have a Python program in which I would like to have a voice report certain events, but I don't want to pause the main loop of my program while the voice speaks. I thought I could achieve this by running pyttsx3 in a separate thread (as shown below), but it is not working. The whole program pauses as the voice reads. Are there any workarounds or better solutions for this?
import pyttsx3
from threading import Thread
from time import sleep
def text_to_speech(engine, txt):
print(f"Speaking: {txt}")
engine.say(txt)
engine.runAndWait()
engine = pyttsx3.init()
for n in range(1,21):
sleep(.1)
if n % 5 == 0:
txt = f'{n} is divisible by 5.'
Thread(target=text_to_speech(engine, txt)).start()
else:
print(n)