2016-08-21 115 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