Python-同时运行代码(TTS和打印功能)

时间:2018-10-12 20:01:26

标签: python python-3.x multithreading

返回文本后,如何同时运行以下代码或运行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))

1 个答案:

答案 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()