如何在讲话中停止pyttsx3?
how to stop pyttsx3 in middle of speech?
我想停止 pyttsx3。我尝试终止多进程,但响应时间变慢,我不知道为什么。这是代码:
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()
是否有任何选项或替代方法可以在中间停止讲话?
尝试使用 try, except 语句,在这种情况下,当按下 Ctrl + C
时,它将终止进程。
def speak(audio):
try:
p = Process(target=speakfunc, args=(audio,))
p.start()
except KeyboardInterrupt:
p.terminate()
p.join()
try:
#abunchoflines
except('''nameoferror'''):
#anotherbunchoflines
等于说“试试(#abunchoflines),如果有错误抛出,名称为error((偶尔可以为空,解释'all errors')),执行(#anotherbunchoflines) ”不太方便,因为 ctrl+c
通常等于 sys. exit(0)
,甚至 os._exit(0)
。有一个 pynput
模块,具体来说,pynput.keyboard
可以解决 multi-(threading/processing) 的问题。子类别? Key
和 Listener
.
样本(无多(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()
我想停止 pyttsx3。我尝试终止多进程,但响应时间变慢,我不知道为什么。这是代码:
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()
是否有任何选项或替代方法可以在中间停止讲话?
尝试使用 try, except 语句,在这种情况下,当按下 Ctrl + C
时,它将终止进程。
def speak(audio):
try:
p = Process(target=speakfunc, args=(audio,))
p.start()
except KeyboardInterrupt:
p.terminate()
p.join()
try:
#abunchoflines
except('''nameoferror'''):
#anotherbunchoflines
等于说“试试(#abunchoflines),如果有错误抛出,名称为error((偶尔可以为空,解释'all errors')),执行(#anotherbunchoflines) ”不太方便,因为 ctrl+c
通常等于 sys. exit(0)
,甚至 os._exit(0)
。有一个 pynput
模块,具体来说,pynput.keyboard
可以解决 multi-(threading/processing) 的问题。子类别? Key
和 Listener
.
样本(无多(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()