Python pyttsx,如何使用外部循环

2024-03-28 08:47:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的程序中,我需要类(可以是一些线程)来检查诸如“say_list”之类的列表,当其他类向其中添加一些文本时,pyttsx会说出该文本。 我在pyttsxdocs中搜索,找到了一些外部循环特性,但我找不到正确工作的示例。 我想要这样的东西:

import pyttsx
import threading

class VoiceAssistant(threading.Thread):
    def __init__(self):
        super(VoiceAssistant, self).__init__()
        self.engine = pyttsx.init()
        self.say_list = []

    def add_say(self, msg):
        self.say_list.append(msg)

    def run(self):
        while True:
            if len(self.say_list) > 0:
                self.engine.say(self.say_list[0])
                self.say_list.remove(self.say_list[0])


if __name__ == '__main__':
    va = VoiceAssistant()
    va.start()

谢谢。在


Tags: 文本importself程序ifinitdefmsg
1条回答
网友
1楼 · 发布于 2024-03-28 08:47:26

我可以使用python内置的Queue类得到正确的结果:

import pyttsx
from Queue import Queue
from threading import Thread

q = Queue()

def say_loop():
    engine = pyttsx.init()
    while True:
        engine.say(q.get())
        engine.runAndWait()
        q.task_done()

def another_method():
    t = Thread(target=say_loop)
    t.daemon = True
    t.start()
    for i in range(0, 3):
        q.put('Sally sells seashells by the seashore.')
    print "end of another method..."

def third_method():
    q.put('Something Something Something')

if __name__=="__main__":
    another_method()
    third_method()
    q.join() # ends the loop when queue is empty

上面是一个简单的例子。它使用“queue/consumer”模型来允许不同的函数/类访问同一个队列,然后在队列中有项时执行一个worker。应该很容易适应你的需要。在

进一步阅读队列:https://docs.python.org/2/library/queue.html 你在这个界面上似乎已经有了一个你想要的线索。在

下面是您代码的修改版本:

^{pr2}$

相关问题 更多 >