pythonpython-3.xmultiprocessingpyttsxpyttsx3

how to stop pyttsx3 in middle of speech?


I want to stop pyttsx3. I tried killing multiprocess but then the response time gets slow I dont know why. Here is the code:

import pyttsx3
from multiprocessing import Process

def speakfunc(audio):
    engine = pyttsx3.init()
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[0].id)
    engine.setProperty('rate', 140)
    engine.say(audio)
    engine.runAndWait()



def speak(audio):
    p = Process(target=speakfunc, args=(audio,))
    p.start()

    while p.is_alive():
         if keyboard.is_pressed('q'):
             p.terminate()
         else:
             continue
    p.join()

Are there any option or alternative to stop speech in middle?


Solution

  • Try using a try, except statement as in this case when Ctrl + C is pressed it is going to terminate the process.

    def speak(audio):
        try:
            p = Process(target=speakfunc, args=(audio,))
            p.start()
        except KeyboardInterrupt:
            p.terminate()
    
        p.join()