0

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?

Prashasth Nair
  • 167
  • 2
  • 12

2 Answers2

0

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()
JaniniRami
  • 493
  • 3
  • 11
  • hey, I tried it but pyttsx is not stoping in middle. It is not taking Ctrl + C in middle of speech. And the delay is still there :( – Prashasth Nair Dec 21 '20 at 14:45
0
try:
#abunchoflines
except('''nameoferror'''):
#anotherbunchoflines

Is equal to saying "try (#abunchoflines), if there is an error raised with the name of error((occasionally, it can be blank, interpreting 'all errors')), execute (#anotherbunchoflines)." not so handy since ctrl+c typically is equal to sys. exit(0), or even os._exit(0). There is a pynput module, specifically, pynput.keyboard that does the trick with multi-(threading/processing). The sub-categories? Key and Listener.

Sample(without multi-(threading/processing)):

from pynput.keyboard import Key, Listener
def show(key):
    print('\nYou Entered {0}'.format( key))
    if key == Key.delete:#delete key pressed
    return False#stop listener
while 1:#collect events until released
    with Listener(on_press = show) as listener:
         listener.join()
Qihua Huang
  • 34
  • 1
  • 2