python - 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__
在这种情况下如何使用该属性?
非常感谢!
解决方案
这是使用谷歌识别器的代码,它将不断地监听直到你终止:
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:
在那里你可以选择要阅读更多关于哪个实现,这个包的文档非常好。
推荐阅读
- github - PHP构建失败:无法打开流:没有这样的文件或目录
- angular - 如何在控制台中显示 Angular 组件而不是 main.js 中日志的正确位置?
- reactjs - React Material Theme 不被外部依赖继承
- python - 使用格式构建报告
- web-deployment - AddRazorRuntimeCompilation 导致部署问题
- python - 未收到 Wocomerce webhook
- regex - 需要解析日志并创建 2 个受控组,其中一组具有另一组的文本
- c++ - 在 C++ Struct 查询中初始化新成员变量
- traefik - Traefik 重写路径
- c# - C# Selenium Edge - 获取 Edge 浏览器的运行实例