[从语音识别器中使用麦克风时获取AttributeError:__ enter __

问题描述 投票:2回答:2

下面的代码。当我研究文档时,如果我们使用麦克风,则必须安装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__

python speech-recognition
2个回答
2
投票

AttributeError: __enter__表示您正在尝试使用不支持上下文管理器协议的对象进入上下文管理器块;它没有__enter__方法。

特别是,您正在尝试在sr.Microphone语句中打开with类。根据documentation,您需要向上下文管理器提供实例sr.Microphone()

with sr.Microphone() as source:
    ...

0
投票

它会一直监听直到您终止: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()
© www.soinside.com 2019 - 2024. All rights reserved.