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

标签 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))

最佳答案

如果您希望您的 tts 函数在打印响应后运行,那么简单的解决方案是,让 main 在调用 tts 之前打印出响应。但是为了获得更大的灵 active 和更好的提示响应能力,您可以为 tts 调用使用单独的线程。

threading 模块提供了一个Timer,它是Thread 的子类。 Timer 有一个 interval 参数,用于在执行目标函数之前添加一个 sleep 。如果需要,您可以使用它来添加延迟,或者如果您不需要此功能,则只需使用 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()

关于Python - 同时运行代码(TTS 和打印功能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52786288/

相关文章:

python - 从文件列表中读取文件

python - 查询 sqlite 到 LIKE 但整个单词

python - PyMongo 驱动程序是否聚合数据

python - 即使我在 python 中将变量声明为 float,也会发生舍入

python-3.x - 如何使 cv2.videoCapture.read() 更快?

c++ - 停止 Thrift 服务器(TSimpleServer)

python - 我如何确定 vim 缓冲区是否已从 vim 的 python api 中列出或未列出?

python-3.x - 如何删除 3d 数组上包含 nan 元素的子数组并保留形状?

Python:tqdm 进度条停留在 0%

C++ fork()、多线程和操作系统的概念