Skip to main content
 首页 » 编程设计

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

2024年12月31日9zfyouxi

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