0

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)
Tim Huff
  • 44
  • 4

1 Answers1

0

The top answer found in this post was helpful in resolving this problem: Running pyttsx3 inside a game loop

It works well, but so far, I have yet to figure out how to interrupt the speaking, so it is not perfect.

Tim Huff
  • 44
  • 4