Runtime error occurs when using a thread for pyttsx3 audio function in a while loop

I am working on Vision-Based American Sign Language Converter Application using MediaPipe and OpenCV in python. As you may know, in webcam, we use a while loop for continuous hand detection of our hand. Now the problem was that when I added audio function for the detected gesture using pyttx3 the webcam always got struck during the execution of pyttsx3 engine function.
To resolve that issue, I used threading and made a thread for that audio related part and put that thread inside that webcam while loop.
But now the problem is that, the "Runtime Error: loop is already started" continuously appears in the terminal.

I have made a model code for my problem. I know the problem is that the threading function is calling the speak function again and again, and inside the speak function I have used ‘runAndWait()’ method, which is giving the error that loop is already started.
Please look into this matter. I have been looking for the solution for two weeks. I have tried every possible thing on my own.

import pyttsx3
from threading import Thread
import random


engine = pyttsx3.init()
def speak(text):
    engine.say(text)
    engine.runAndWait()

while True:
    l = ['A', 'B', 'C', 'D', 'E']
    a = random.choice(l)
    print(a)
    
    t = Thread(target=speak, args=(a,))
    t.start()
    #engine.stop()

Source: Python-3x Questions

LEAVE A COMMENT