语音识别循环

时间:2015-06-19 10:13:58

标签: python python-2.7

我正在尝试编写语音识别代码,该代码从麦克风接收语音并处理直到说“停止”。该代码适用于第一个语音,但随后出现错误。我写的代码如下:

import speech_recognition as sr
import webbrowser
r = sr.Recognizer()


with sr.Microphone() as source:                
    while True:
        audio = r.listen(source)
        print("You said " + r.recognize(audio)) 
        if r.recognize(audio)=="Facebook":
            webbrowser.open('https://www.facebook.com')
        if r.recognize(audio)=="Google":
            webbrowser.open('https://www.google.co.uk')
        if r.recognize(audio)=="Stop":
            break

我得到的错误是:

You said Facebook
Traceback (most recent call last):
File "C:/Work/Scripts/SpeechRecognition/Speech.py", line 9, in <module>
print("You said " + r.recognize(audio)) # listen for the first phrase and extract it into audio data
File "C:\Users\roradhak.NDS-UK\AppData\Roaming\Python\Python27\site-packages\speech_recognition\__init__.py", line 324, in recognize
raise LookupError("Speech is unintelligible")

LookupError:言语难以理解

Process finished with exit code 1

2 个答案:

答案 0 :(得分:2)

我认为问题可能是您在同一输入上多次调用recognize并且第一次调用已经消耗了音频。您可以引入一个额外的变量+ add try / catch来处理LookupError。

with sr.Microphone() as source:                
    while True:
        audio = r.listen(source)
        try:
            result = r.recognize(audio)
            print("You said " + result)
            words = result.lower()
            if words=="facebook":
                webbrowser.open('https://www.facebook.com')
            if words=="google":
                webbrowser.open('https://www.google.co.uk')
            if words=="stop":
                break
        catch LookupError:
            print("Please, speak more clearly")

答案 1 :(得分:1)

您需要捕获异常:

def recognize(audio):
    try:
        return r.recognize(audio)
    except LookupError, e:
        print e
        return ''

然后:

with sr.Microphone() as source:                
    while True:
        audio = r.listen(source)
        words = recognize(audio)
        print("You said " + words) 
        if words == "Facebook":
            webbrowser.open('https://www.facebook.com')
        elif words =="Google":
            webbrowser.open('https://www.google.co.uk')
        elif words == "Stop":
            break