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

Python Speech Recognition模块报错:'NoneType'无close属性如何解决?

语音转文本项目AttributeError问题排查与解决

问题场景

尝试使用Python结合麦克风实现语音转文本功能,运行代码时出现AttributeError错误。

原代码

import pyttsx3
import speech_recognition as sr
import webbrowser
import datetime
import pyjokes

def sptext():
    # Create a recognizer instance
    recognizer = sr.Recognizer()

    # Use the default microphone as the audio source
    with sr.Microphone() as source:
        print("Listening...")

        try:
            # Adjust for ambient noise before listening
            recognizer.adjust_for_ambient_noise(source)

            audio = recognizer.listen(source)

            # Use Google Speech Recognition to transcribe the audio to text
            text = recognizer.recognize_google(audio)
            print(f"You said: {text}")
        except sr.UnknownValueError:
            print("Sorry, I could not understand what you said.")
        except sr.RequestError as e:
            print(f"Request error: {e}")
        
        try:
            # Close the audio stream
            source.stream.close()
        except AttributeError:
            pass

sptext()

报错信息

During handling of the above exception, another exception occurred:   

Traceback (most recent call last):  File "C:\computer_science\Python Lessons\Projects\7-Voice Assitant\ch1\main.py", line 68, in <module>
    sptext()  File "C:\computer_science\Python Lessons\Projects\7-Voice Assitant\ch1\main.py", line 44, in sptext
    with sr.Microphone() as source:
  File "C:\Users\Asus\AppData\Roaming\Python\Python311\site-packages\speech_recognition\__init__.py", line 189, in __exit__
    self.stream.close()
    ^^^^^^^^^^^^^^^^^AttributeError: 'NoneType' object has no attribute 'close'

问题原因与解决方法

错误根源在于你手动调用了source.stream.close(),而with语句本身是上下文管理器,会自动处理sr.Microphone()的资源生命周期:进入块时初始化音频流,退出时自动调用关闭方法清理资源。

你额外的手动关闭操作会提前将source.stream置为None,当with块执行到__exit__方法时,再次尝试关闭已经不存在的流,就触发了AttributeError。

只需删除手动关闭流的代码段即可解决问题,修正后的代码如下:

import pyttsx3
import speech_recognition as sr
import webbrowser
import datetime
import pyjokes

def sptext():
    # Create a recognizer instance
    recognizer = sr.Recognizer()

    # Use the default microphone as the audio source
    with sr.Microphone() as source:
        print("Listening...")

        try:
            # Adjust for ambient noise before listening
            recognizer.adjust_for_ambient_noise(source)

            audio = recognizer.listen(source)

            # Use Google Speech Recognition to transcribe the audio to text
            text = recognizer.recognize_google(audio)
            print(f"You said: {text}")
        except sr.UnknownValueError:
            print("Sorry, I could not understand what you said.")
        except sr.RequestError as e:
            print(f"Request error: {e}")

sptext()

补充说明

sr.Microphone()的上下文管理器已经封装了完整的资源清理逻辑,包括异常情况下的流关闭,无需手动干预。保留原有的异常捕获逻辑即可处理语音识别过程中的常见错误(无法识别语音、请求失败等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 21:32:16