如何让pyttsx3读取一行但不等待

How to get pyttsx3 to read a line but not wait

我有一个聊天机器人,我想通过声音阅读它对用户输入的响应。然而,pyttsx3 使程序等待它停止使用 runAndWait() 说话。这会导致用户在文本完成之前键入,从而导致提示中出现奇怪的外观。

有办法解决这个问题吗?

你需要深入研究多线程。

大致如下:

import concurrent.futures
import sys
import pyttsx3
from time import sleep

def typing(text):
    for char in text:
        sleep(0.04)
        sys.stdout.write(char)
        sys.stdout.flush()

def textToSpeech(text):
    engine = pyttsx3.init()
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[0].id)
    engine.setProperty('rate', 220)
    engine.say(text)
    engine.runAndWait()
    del engine

def parallel(text):
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        future_tasks = {executor.submit(textToSpeech, text), executor.submit(typing, text)}
        for future in concurrent.futures.as_completed(future_tasks):
            try:
                data = future.result()
            except Exception as e:
                print(e)

parallel("Speak this!")
sleep(4.0)