2016-08-21 59 views
0

在我的程序中,我需要类(可以是某个线程)来检查一些列表,比如“say_list”,当其他类添加一些文本时,pyttsx会说出文本。 我在pyttsx docs搜索,我发现一些外部循环功能,但我找不到正确工作的示例。 我想要这样的:Python pyttsx,如何使用外部循环

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() 

谢谢。

回答

1

我可以通过使用内置的Queue类Python的正确的结果:

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 

上面是一个简单的例子,我刮起。它使用'队列/消费者'模型来允许单独的函数/类访问同一个队列,然后一个在任何时候队列中都会执行的worker。应该很容易适应您的需求。

进一步阅读有关队列:https://docs.python.org/2/library/queue.html 似乎有在您链接到的文档此接口,但它似乎像你已经在单独的线程赛道上如此,这似乎更接近你想要的东西。

而且这里是你的代码的修改后的版本:

import pyttsx 
from Queue import Queue 
import threading 

class VoiceAssistant(threading.Thread): 
    def __init__(self): 
     super(VoiceAssistant, self).__init__() 
     self.engine = pyttsx.init() 
     self.q = Queue() 
     self.daemon = True 

    def add_say(self, msg): 
     self.q.put(msg) 

    def run(self): 
     while True: 
      self.engine.say(self.q.get()) 
      self.engine.runAndWait() 
      self.q.task_done() 


if __name__ == '__main__': 
    va = VoiceAssistant() 
    va.start() 
    for i in range(0, 3): 
     va.add_say('Sally sells seashells by the seashore.') 
    print "now we want to exit..." 
    va.q.join() # ends the loop when queue is empty 
+0

感谢。它帮助很多。 但第二个代码没有工作,但第一个工作正常 – destrat18

+0

什么似乎是与第二个问题?它对我来说运行良好。 – shark3y

+0

我不知道。当我运行它pyttsx不说任何事情。第一个人工作,并帮助我很多。所以我留下第二个:D。我希望你能用我的英文不好理解我的话 – destrat18