AttributeError: __Enter__ - How to use?

AttributeError: __Enter__ - How to use?

我正在尝试在Python中制作一个简单的语音识别工具,并尝试了以下代码:

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone as source:
print ("Speak into the microphone")
audio = r.listen(source) 

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-10651df1693e> in <module>
----> 1 with sr.Microphone as source:
      2     print ("Speak into the microphone")
      3     audio = r.listen(source)

AttributeError: __enter__ 

我希望有人能够阐明如何在这种情况下使用 __enter__ 属性?

非常感谢!

下面是使用 google 识别器的代码,它将持续监听直到您终止:

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()

如果您只想听一个实例,请删除:

while True:

Here is the link to the speech recignition documentation

在那里你可以select阅读更多关于哪个实现,这个包的文档非常好。