获取属性错误:\从语音识别器使用麦克风时,请输入\uuuu

2024-05-18 16:17:11 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下。当我研究文档时,如果我们使用麦克风,必须安装语音识别。所以我安装了它,但仍然有这个错误

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中 使用高级话筒作为源: AttributeError:__enter__


Tags: 代码文档sourcedatadefas错误with
3条回答

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

具体来说,您正试图在with语句中打开sr.Microphone类。根据documentation,您需要向上下文管理器提供一个实例sr.Microphone()

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

对于所有未能解决此问题的人:

不要使用类sr.Microphone作为源,而是使用对象sr.Microphone()

因为我们应该使用speechRecognition对象而不是类本身来调用方法

它会一直监听,直到您终止: 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()

相关问题 更多 >

    热门问题