Search code examples
pythonpyttsx

How to get pyttsx3 to read a line but not wait


I have a chatbot that I want to read with sound the responses to the user's inputs. However, pyttsx3 makes it so that the program waits for it to stop speakign with runAndWait(). This causes the user to type before the text is finished causing a weird look in the prompt.

n

Is there a way to get around this?


Solution

  • You need to dig into multi threading.

    Something along the lines of:

    import concurrent.futures
    import sys
    import pyttsx3
    from time import sleep
    
    def typing(text):
        for char in text:
            sleep(0.04)
            sys.stdout.write(char)
            sys.stdout.flush()
    
    def textToSpeech(text):
        engine = pyttsx3.init()
        voices = engine.getProperty('voices')
        engine.setProperty('voice', voices[0].id)
        engine.setProperty('rate', 220)
        engine.say(text)
        engine.runAndWait()
        del engine
    
    def parallel(text):
        with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
            future_tasks = {executor.submit(textToSpeech, text), executor.submit(typing, text)}
            for future in concurrent.futures.as_completed(future_tasks):
                try:
                    data = future.result()
                except Exception as e:
                    print(e)
    
    parallel("Speak this!")
    sleep(4.0)