错误处理 speech_recognition WaitTimeOutError

error handling speech_recognition WaitTimeOutError

当我尝试运行这个代码时

  import speech_recognition as sr  #importing sr
r = sr.Recognizer()

with sr.Microphone() as source:
    print("speak into mic")
    audio = r.listen(source,timeout=2)


try:
    print("Transcription:" + r.recognize_google(audio))
except sr.UnknownValueError:
    print("Audio Unintelligible")

except sr.RequestError as e:
    print("cannot obtain results : {0}".format(e))

except sr.WaitTimeoutError as k :
    print("time out")    #error handler for time out error

当我 运行 上面的代码出现这样的错误时

speak

 into mic
Traceback (most recent call last):
  File "C:/Users/punna/PycharmProjects/alex/alex.py", line 6, in <module>
    audio = r.listen(source,timeout=2)
  File "C:\Users\punna\Anaconda3\lib\site-packages\speech_recognition\__init__.py", line 544, in listen
    raise WaitTimeoutError("listening timed out while waiting for phrase to start")
speech_recognition.WaitTimeoutError: listening timed out while waiting for phrase to start

我写了异常,但它又报错了

谁能帮帮我

这是因为您将超时保持在有限的时间内。尝试没有超时或保持超时至少超过 5

这可能会有所帮助我刚刚添加了 return "none" 声明,以便在出现问题时 return 成为 none 我还添加了 phrase_time_limit to 5 and query = r.recognize_google(voice,language='en-in') 这个语句来识别用户说出的单词变成一个变量而不是这个语句 print("Transcription:" + r.recognize_google(audio)) 然后它起作用试试这可能对你有帮助

 r = sr.Recognizer()
 with sr.Microphone() as audio:
     speak('Listening...')
     r.pause_threshold = 1
     voice = r.listen(audio,timeout=1,phrase_time_limit=5)
 try:
     print("Thinking...")
     query = r.recognize_google(voice,language='en-in')
     print("Transcription:"+query) 

 except Exception as e:
     print("I am Sorry There is an error while i am recognizimg your command")
     return "none"
 return query
def takecommand():
    try:
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Listing.......")
            r.pause_threshold = 1
            audio = r.listen(source, timeout=1, phrase_time_limit=5)
    except Exception as e:
        speak("error in my files sir restarting")
        speak("completed")
        return "none"

    try:
        print("Recognize......")
        qureay = r.recognize_google(audio, language='en-in')
        print("user said:" +qureay)

    except Exception as e:
        speak("Say That Again Please...")
        return "none"
    return qureay