0

我正在创建一个 DIY 虚拟助手,以便在 python 中获得乐趣和锻炼。尝试在线程中使用 engine.say 然后在我的主程序中再次使用它时遇到问题。

我已经尝试使用 pyttsx 文档中的 engine.endLoop() 和其他可能的解决方案(engine.stop()、engine.endLoop() 等),但我仍然没有成功。我在一些关于 asyncio 的答案中看到了。但是使用 pip 我无法安装它,而且我不太确定它会解决我的问题。

功能:

def portport():

        ser = serial.Serial('COM4',9600)
        raw_data = ser.read(9)
        msg = str(raw_data[3:8])
        print msg
        ser.close()
        return msg

def Comm_Connection():

    print("CommConns started")

    while True:
        global conn

        try:
            conn, addr = SERVER.accept()
            Live_Conns.append(conn)

            Server_Send = "Connection established successfully"
            Server_Send = pickle.dumps(Server_Send)
            Live_Conns[-1].send(Server_Send)

            temp = conn.recv(1024)
            Server_Receive = pickle.loads(temp)

            Live_Name.append(Server_Receive)

            Connections = (Live_Name[-1], "Connected")

            engine.say(Connections)
            engine.runAndWait()

        except socket.error as socketerror:
            continue
        except socket.timeout:
            continue

“主”程序:

Server_Up = threading.Thread(target = Comm_Connection)
Server_Up.start()

while True:  
    engine = pyttsx.init()  

    time.sleep(7)
    engine.say("Goodmorning")
    engine.runAndWait() 

我得到的错误是:

raise RuntimeError('运行循环已经开始')

RuntimeError:运行循环已经开始

4

2 回答 2

2

看起来您的while True循环正在尝试启动和运行 pyttsx 引擎,同时它正在Comm_Connection循环内运行。

请注意,pyttsx 使用其自己的支持回调和手动迭代的内部引擎,因此您可能会考虑按照以下从 docs 修改的示例的行更多地重写您的应用程序:

engine = pyttsx3.init()
engine.say('The quick brown fox jumped over the lazy dog.', 'fox')
engine.startLoop(False)
# engine.iterate() must be called inside Server_Up.start()
Server_Up = threading.Thread(target = Comm_Connection)
Server_Up.start()
engine.endLoop()

免责声明:我已经玩过这个库,知道手动迭代方法确实有效,但不足以理解您的特定需求,所以 YMMV。

于 2019-11-19T22:56:36.533 回答
0

因为这是一个常见问题,所以我为我的程序找到了解决方案。使用私有变量判断循环是否已经开始,如果正在使用则结束循环engine._inLoop-

while True:  
    engine = pyttsx.init()  

    time.sleep(7)
    engine.say("Goodmorning")
    engine.runAndWait() 

    if engine._inLoop:
        engine.endLoop()
于 2021-01-28T03:35:25.537 回答