Search code examples
pythonpython-3.xwindowsspeech-recognitionpyaudio

Speech recognition error can't find Microphone as source


I'm working on the listening part of a speech recognition project. Currently, I'm stuck with this error message when I run the code.

import speech_recognition as sr

robot_ear = sr.Recognizer()
with sr.Microphone(device_index=1) as mic:
    #robot_ear.adjust_for_ambient_noise(mic)
    print("Robot: I'm listening")
    audio = robot_ear.listen(mic)

try:
    you = robot_ear.recognize_google(audio)
except:
    you = ""

print(you)

This is the error:

Robot: I'm listening
Traceback (most recent call last):
  File "C:\Users\trung\Documents\Python 3\nghe.py", line 7, in <module>
    audio = robot_ear.listen(mic)
            ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\trung\AppData\Local\Programs\Python\Python311\Lib\site-packages\speech_recognition\__init__.py", line 465, in listen
    assert source.stream is not None, "Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"
           ^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\trung\Documents\Python 3\nghe.py", line 4, in <module>
    with sr.Microphone(device_index=1) as mic:
  File "C:\Users\trung\AppData\Local\Programs\Python\Python311\Lib\site-packages\speech_recognition\__init__.py", line 189, in __exit__
    self.stream.close()
    ^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'close'

I tried setting the Microphone manually by looking for its index, which appears to be index 1, but doesn't seem to fix the problem.


Solution

  • It appears that my microphone access setting in Windows 11 is off. I just needed to go to Start > Settings > Privacy & security > Microphone and make sure Microphone access is turned on, then it's working now.