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

1

5

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.

Succeed answered 17/5, 2023 at 14:5 Comment(1)
That should be with sr.Microphone() as source: - you're missing the parentheses.Bonfire
V
16

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

Venn answered 17/5, 2023 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.