错误处理Speech_recognition WaitTimeOutError

时间:2019-12-27 05:46:21

标签: python python-3.x speech-recognition pyaudio

当我尝试运行此代码时

  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

我写了异常,但它再次给出了错误

谁能帮我

2 个答案:

答案 0 :(得分:0)

这是因为您将超时保持了有限的时间。尝试不设置超时或将超时保持至少5

答案 1 :(得分:0)

这可能有助于我刚刚添加了 return "none" 语句,以便在出现问题时返回 none,并且我还将短语时间限制添加到 5 和 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