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

Python报错'NoneType' object has no attribute 'close',发音评分助手代码排查

问题分析与修复方案

错误含义

'NoneType' object has no attribute 'close' 表示代码尝试调用一个值为None的对象的close()方法,但None(空值)不存在这个方法。本质是某个本该是可操作设备对象的变量,实际没有成功初始化,变成了空值。

代码问题

问题出在麦克风初始化和上下文管理器的使用上:

  • 当系统没有可用麦克风设备,或者speech_recognition库无法正确识别麦克风时,sr.Microphone()会返回None。
  • 后续的with microphone as source语句会尝试对None执行上下文管理器的退出逻辑(内部会调用close()),从而触发错误。
  • 原代码的try-except只覆盖了语音识别部分,没有处理麦克风初始化、音频录制阶段的异常。

修复后的代码

import speech_recognition as sr

def evaluate_pronunciation(phrase):
    recognizer = sr.Recognizer()
    try:
        # 初始化麦克风,捕获初始化失败的异常
        microphone = sr.Microphone()
        if not microphone:
            raise ValueError("No available microphone detected")
        
        with microphone as source:
            recognizer.adjust_for_ambient_noise(source)
            audio = recognizer.listen(source)
        
        spoken_text = recognizer.recognize_google(audio)
        print(f"You said: {spoken_text}")
        
        if phrase.lower() == spoken_text.lower():
            score = 1.0
            suggestion = ""
        else:
            score = 0.0
            suggestion = f"You said '{spoken_text}', but the correct phrase is '{phrase}'."
        
        return score, suggestion
    
    except sr.UnknownValueError:
        suggestion = "Sorry, we could not understand what you said. Please try again."
        score = 0.0
        return score, suggestion
    except sr.RequestError:
        suggestion = "Could not connect to the speech recognition service. Please check your network."
        score = 0.0
        return score, suggestion
    except ValueError as e:
        suggestion = str(e)
        score = 0.0
        return score, suggestion
    except Exception as e:
        suggestion = f"An error occurred: {str(e)}"
        score = 0.0
        return score, suggestion

# Example usage
phrase = "hello world"
score, suggestion = evaluate_pronunciation(phrase)
print(f"Your score is {score}")
print(suggestion)

修复要点

  • 新增麦克风初始化的检查,判断是否成功获取到麦克风设备。
  • 将麦克风初始化、音频录制的逻辑也纳入try-except块,捕获初始化失败的ValueError以及其他可能的异常。
  • 补充捕获sr.RequestError,处理谷歌语音识别服务连接失败的情况。
  • 通用异常捕获作为兜底,避免程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:55:03