我怎么能让python等到我完成讲话?

时间:2015-06-19 12:54:47

标签: python python-2.7 speech-recognition pyttsx

我正在编写一个程序来识别来自麦克风的语音,代码将相应地处理。我为此目的编写的代码如下。

import speech_recognition as sr
import webbrowser
import pyttsx
from time import sleep

engine = pyttsx.init()
engine.setProperty('rate', 70)
r = sr.Recognizer()

def recognize(audio):
    try:
        return r.recognize(audio)
    except LookupError, e:
        print e
    return ''
with sr.Microphone() as source:
    while True:
        engine.say("Hi How can i help you ?")
        sleep(0.15)
        print "Start Speaking"
        audio = r.listen(source)
        words = recognize(audio)
        print("You said " + words)
        if words == "Facebook":
            engine.say("Shall i open the Facebook page for you ?")
            engine.runAndWait()
            audio = r.listen(source)
            words = recognize(audio)
            if words == "Yes":
                webbrowser.open('https://www.facebook.com')
        elif words == "stop":
            break

在这里我也试过睡觉,但在发动机说话之前,我可以看到文字开始说话打印。而不是睡眠,有没有什么好方法可以在麦克风中捕捉语音并等到说些什么或长时间的沉默?

1 个答案:

答案 0 :(得分:2)

此方法:

        engine.runAndWait()

等待演讲完成。您不仅需要在engine.say("Shall i open the Facebook page for you ?")之后使用它,还需要在engine.say("Hi How can i help you ?")之后使用它  而不是sleep