Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve TypeError: 'type' object does not support context manager protocol?

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.

like image 508
Probal Kar Avatar asked Jun 07 '26 13:06

Probal Kar


1 Answers

try changing with sr.Microphone as source: to with sr.Microphone() as source:

like image 75
pippo1980 Avatar answered Jun 10 '26 01:06

pippo1980



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!