我最近在做这个基本的 AI 项目,我正在使用语音识别来处理听力部分。目前,我在运行代码时遇到此错误消息。
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)
这是错误:
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'
我尝试通过查找它的索引来手动设置麦克风,它似乎是索引 1,但似乎没有解决问题。