Uberi / speech_recognition

Speech recognition module for Python, supporting several engines and APIs, online and offline.
https://pypi.python.org/pypi/SpeechRecognition/
BSD 3-Clause "New" or "Revised" License
8.31k stars 2.4k forks source link

UnknownValueError screws infinite listening loop #309

Open faxe1008 opened 6 years ago

faxe1008 commented 6 years ago

I am building a speech recognition (https://github.com/Uberi/speech_recognition) using the following method:

self.Recognizer = sr.Recognizer() self.Recognizer.energy_threshold = 8000

def start_recognition(self):
    while self.Active:
        with sr.Microphone(self.MICROPHONE_INDEX) as source:
            audio = self.Recognizer.listen(source)

            recognized_text = self.Recognizer.recognize_google(audio)
            matching_command = self.find_matching_command(recognized_text.lower())

            print('Recognized Text: %s ' % recognized_text)
            if matching_command is not None:
                print('Matching Command: %s' % matching_command.__class__.__name__)
                response_text = matching_command.execute()
                self.speak(response_text)
                print(response_text)

That works just perfectly if I am testing right after I started to run the application but it stops working right after a few seconds of saying nothing I get this error:

Traceback (most recent call last):

 File "C:/Users/****/PycharmProjects/****/****/****.py", line 61, in <module>
    jc.start_recognition()
  File "C:/Users/****/PycharmProjects/****/****/****.py", line 46, in start_recognition
    recognized_text = self.Recognizer.recognize_google(audio)
  File "C:\Users\****\AppData\Local\Programs\Python\Python36\lib\site-packages\speech_recognition\__init__.py", line 780, in recognize_google
    if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
speech_recognition.UnknownValueError

How do I fix this behaviour?

airrakeshkumarsharma commented 6 years ago

Yes, I am also getting the same issue.

palikar commented 5 years ago

Hi @faxe1008, your code looks wrong the recognized_text = self.Recognizer.recognize_google(audio) part must be outside of the with sr.Microphone(self.MICROPHONE_INDEX) as source:. The correct code would then be

with sr.Microphone(self.MICROPHONE_INDEX) as source:
        audio = self.Recognizer.listen()
recognized_text = self.Recognizer.recognize_google(audio)

Also it may be resonable to check if you have actually recorded any audio with

if(audio is not None):
      recognized_text = self.Recognizer.recognize_google(audio)