Python SpeechRecognition AttributeError: __exit__ with sr.Microphone()

Python SpeechRecognition AttributeError: __exit__ with sr.Microphone()

我正在尝试使用 SpeechRecognition 3.5 将语音转换为文本。我正在使用 Python 2.7.13。我查找了一些使用此模块的示例,我找到的所有示例包括:

r = sr.Recognizer()
with sr.Microphone() as source:
    audio = r.listen(source)

但是当我运行这个它总是吐出这个错误

AttributeError: __exit__

我不确定如何解决这个问题,因为

with sr.Microphone() as source:

正在寻找 exit 方法,但找不到。所以我试着去掉 with 关键字,所以它看起来像这样:

source = sr.Microphone()
audio = r.listen(source)

但它随后向我吐出一个 AssertionError。

AssertionError: Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?

我不确定从这里开始做什么。谁能向我解释为什么这不起作用?

编辑:

sr.Microphone -> sr.Microphone()

编辑 2:

错误是因为我没有导入PyAudio(这是必需的)而我没有意识到。现在我无法阻止它录制麦克风。

添加, phrase_time_limit=10 //10 秒

例如:

with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source,timeout=1,phrase_time_limit=10)

sr.Microphone 作为来源:

print("say something!")

如果你这样写那么你得到了属性错误,所以添加替换 sr.Microphonesr.Microphone()

使用

sr.Microphone() as source:

而不是:

sr.Microphone as source: