下面的代码。当我研究文档时,如果我们使用麦克风,则必须安装Speech_Recognition。所以我安装了它,但仍然出现此错误。
def recordAudio():
r = sr.Recognizer()
with sr.Microphone as source:
print('I am listening to you sir.')
audio = r.listen(source)
data = ''
try:
data = r.recognize_google(audio)
print('You said: ' + data)
except sr.UnknownValueError:
print('Voice cannot be recognized.')
except sr.RequestError as e:
print('Req results:' + e)
return data
第54行,在recordAudio中使用sr.Microphone作为来源:AttributeError:__enter__
AttributeError: __enter__
表示您正在尝试使用不支持上下文管理器协议的对象进入上下文管理器块;它没有__enter__
方法。
特别是,您正在尝试在sr.Microphone
语句中打开with
类。根据documentation,您需要向上下文管理器提供实例sr.Microphone()
。
with sr.Microphone() as source:
...
它会一直监听直到您终止:SpeechRecognition
import speech_recognition as sr
def speech_recog():
r = sr.Recognizer()
mic = sr.Microphone()
while True:
with mic as source:
print("Speak...")
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print(f"You said {text}")
except sr.UnknownValueError:
print("Didnt hear that try again")
speech_recog()