返回文本后,如何同时运行以下代码或运行TTS函数?
代码:
def main(q):
# CODE BEFORE THIS.
# TTS IS JUST A SIMPLE TEXT TO SPEECH FUNCTION
time.sleep(random.uniform(0.5, 2))
response = 'BOT: '+ response
# TTS
# SIMULTANEOUSLY RUN BELOW
if(responsetts!=None):
tts(responsetts)
else:
tts(response)
return response
if __name__ == '__main__':
while True:
query=input('U: ')
print(main(query))
答案 0 :(得分:1)
如果您希望在打印响应后运行tts
函数,那么简单的解决方案是在调用main
之前让tts
打印响应。但是,为了获得更大的灵活性和更好的提示响应能力,您可以为tts
调用使用单独的线程。
线程模块提供Timer
,它是Thread
的子类。 Timer
有一个interval
参数,用于在执行目标函数之前添加睡眠。您可以根据需要使用此功能添加延迟,或者如果不需要此功能,只需使用Thread
。我在示例中使用espeak
而不是tts:
import time
import random
import subprocess
from threading import Timer
from functools import partial
def _espeak(msg):
# Speak slowly in a female english voice
cmd = ["espeak", '-s130', '-ven+f5', msg]
subprocess.run(cmd)
def _vocalize(response, responsetts=None, interval=0):
# "Comparisons to singletons like None should always be done with is or
# is not, never the equality operators." -PEP 8
if responsetts is not None:
response = responsetts
Timer(interval=interval, function=_espeak, args=(response,)).start()
def _get_response(q):
time.sleep(random.uniform(0.5, 2))
response = '42'
response = 'BOT: '+ response
return response
def _handle_query(q):
response = _get_response(q)
print(response)
_vocalize(response, interval=0)
def main():
prompt = partial(input, 'U: ')
# alternative to using partial: iter(lambda: input('U: '), 'q')
for query in iter(prompt, 'q'): # quits on input 'q'
_handle_query(query)
if __name__ == '__main__':
main()