我有一个短语列表,我想知道每个短语以给定的速率动态地花费多长时间,这样我就可以在一段时间内将它们均匀分布。
我目前正在利用started-utterance
并finished-utterance
计时,说出每个短语并记录需要多长时间。当然,这样做的缺点是我必须在应用程序加载时说出每个短语,或者在加载并将结果保存到磁盘之前执行此操作,如果短语列表发生更改,这将失效。
import pyttsx
from datetime import datetime
import time
phrases = ['long sentence', 'medium sentence', 'short sentence', 'word']
phrase_lengths = {phrase: 0 for phrase in phrases}
start_time = None
end_time = None
def onStart(name):
global start_time
start_time = datetime.now()
def onEnd(name, completed):
global start_time
global end_time
end_time = datetime.now()
print name, "took", end_time - start_time
phrase_lengths[name] = end_time - start_time
engine = pyttsx.init()
engine.connect('started-utterance', onStart)
engine.connect('finished-utterance', onEnd)
def speak(engine, rate, phrase):
engine.setProperty('rate', rate)
engine.say(p, p)
engine.runAndWait()
for phrase in phrases:
speak(engine, 120, phrase)
time.sleep(3.0)