我正在尝试使用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__
属性?
非常感谢!
您的sr.Microphone
类未定义__enter__
方法,因此不能用作上下文。有关上下文的更多信息:https://docs.python.org/3.8/reference/compound_stmts.html#the-with-statement
这里是使用Google识别器的代码,该代码会不断监听直到您终止: