首页 > 解决方案 > AttributeError: __Enter__ - 如何使用?

问题描述

我正在尝试用 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__在这种情况下如何使用该属性?

非常感谢!

标签: pythonpython-3.xattributesspeech-recognitionmicrophone

解决方案


这是使用谷歌识别器的代码,它将不断地监听直到你终止:

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:

这是语音识别文档的链接

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


推荐阅读