英文:
How to solve TypeError: 'type' object does not support context manager protocol?
问题
I was creating a voice assistant project but I am having a problem with the line with with
command in it.
The code I've written is this
import speech_recognition as sr
import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
def say(text):
speaker.Speak(f"{text}")
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
r.pause_threshold = 1
audio = r.listen(source)
query = r.recognize_google(audio, language="en-in")
print(f"User said: {query}")
return query
if __name__ == "__main__":
print("VS Code")
say("Hello, I am Jarvis A.I.")
while 1:
print("listening...")
text = takeCommand()
say(text)
And the error it always gets is this
VS Code
listening...
Traceback (most recent call last):
File "f:\Jarvis AI\main.py", line 23, in <module>
text = takeCommand()
^^^^^^^^^^^^^
File "f:\Jarvis AI\main.py", line 11, in takeCommand
with sr.Microphone() as source:
TypeError: 'type' object does not support the context manager protocol
I've installed packages in my system like pywin32
, pyaudio
, and speechrecognition
, but now I don't know what to do and how to proceed.
英文:
I was creating a voice assistant project but I am having problem with the line with with
command in it.
The code I've written is this
import speech_recognition as sr
import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
def say(text):
speaker.Speak(f"{text}")
def takeCommand():
r = sr.Recognizer()
with sr.Microphone as source:
r.pause_threshold = 1
audio = r.listen(source)
query = r.recognize_google(audio, language="en-in")
print(f"User said: {query}")
return query
if __name__ == "__main__":
print("VS Code")
say("Hello I am Jarvis A.I.")
while 1:
print("listening...")
text = takeCommand()
say(text)
And the error it always gets is this
VS Code
listening...
Traceback (most recent call last):
File "f:\Jarvis AI\main.py", line 23, in <module>
text = takeCommand()
^^^^^^^^^^^^^
File "f:\Jarvis AI\main.py", line 11, in takeCommand
with sr.Microphone as source:
TypeError: 'type' object does not support the context manager protocol
I've installed packages in my system like pywin32
, pyaudio
and speechrecognition
but now I don't know what to do and how to proceed.
答案1
得分: 7
尝试将 with sr.Microphone as source:
更改为 with sr.Microphone() as source:
英文:
try changing with sr.Microphone as source:
to with sr.Microphone() as source:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论