Search code examples
pythonspeech-recognitionpywin32pyaudio

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.


Solution

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