You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决语音助手中TypeError: 'type'对象不支持上下文管理器协议错误

语音助手项目with语句报错解决方法

问题代码

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)

报错信息

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

解决方法

报错核心原因是sr.Microphone是一个类,而非可直接用于上下文管理器的实例。需要将其实例化,也就是添加括号(),修改后的takeCommand函数如下:

def takeCommand():
    r = sr.Recognizer()
    # 实例化Microphone类
    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

额外优化建议

语音识别过程中可能出现无声音输入、识别失败等情况,添加异常处理可避免程序崩溃:

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Adjusting for ambient noise...")
        # 调整麦克风以适应环境噪音
        r.adjust_for_ambient_noise(source, duration=0.5)
        r.pause_threshold = 1
        try:
            audio = r.listen(source)
            query = r.recognize_google(audio, language="en-in")
            print(f"User said: {query}")
            return query
        except sr.UnknownValueError:
            print("Could not understand audio")
            say("Sorry, I didn't catch that. Could you repeat?")
            return ""
        except sr.RequestError as e:
            print(f"Could not request results from Google Speech Recognition service; {e}")
            say("Sorry, my speech service is down right now.")
            return ""

内容的提问来源于stack exchange,提问作者Probal Kar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 16:40:19