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

复刻Mikael Codes AI助手代码遇AudioSource相关错误求助

语音助手代码运行报错排查

问题背景

跟着Mikael Codes的AI助手开发教程写代码,严格复制初始化章节内容,已安装pocketsphynx、datetime、speech_recognition、pyttsx3等依赖库,但运行时持续出现AssertionError与AttributeError相关报错,尝试查看视频评论区、咨询ChatGPT均未解决。

我的代码

from datetime import datetime
from logging.config import listen
import speech_recognition as sr
import pyttsx3 
import webbrowser
import wikipedia
import wolframalpha
 
# 语音引擎初始化
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) # 0 = 男声, 1 = 女声
activationWord = 'computer' # 唤醒词
 
def speak(text, rate = 120):
    engine.setProperty('rate', rate)
    engine.say(text)
    engine.runAndWait()
 
def parseCommand():
    listener = sr.Recognizer()
    print('正在监听指令')
 
    with sr.Microphone() as source:
        listener.pause_threshold = 2
        input_speech = listener.listen(source)
 
    try: 
        print('正在识别语音...')
        query = listener.recognize_google(input_speech, language='en_gb')
        print(f'识别到的语音内容: {query}')
    except Exception as exception:
        print('我没听清')
        speak('我没听清')
        print(exception)
        return 'None'
 
    return query
 
 
# 主循环
if __name__ == '__main__':
    speak('所有系统正常')
 
    while True:
        # 解析为列表
        query = parseCommand().lower().split()
 
        if query[0] == activationWord:
            query.pop(0)
 
            # 指令列表
            if query[0] == 'say':
                if 'hello' in query:
                    speak('大家好')
                else: 
                    query.pop(0) # 移除say
                    speech = ' '.join(query)
                    speak(speech)

报错信息

正在监听指令
Traceback (most recent call last):
  文件 "c:\Users\_____\.vscode\Python\AI voice\main.py", 第26行, 在 parseCommand 中
    input_speech = listener.listen(source)
                   ^^^^^^^^^^^^^^^^^^^^^^^
  文件 "C:\Users\_______\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\speech_recognition\__init__.py", 第651行, 在 listen 中
    assert source.stream is not None, "Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"
           ^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 音频源必须在监听前初始化,查看``AudioSource``文档;你是不是在``with``语句外使用``source``了?

在处理上述异常期间,又发生了新的异常:

Traceback (most recent call last):
  文件 "c:\Users\______\.vscode\Python\AI voice\main.py", 第48行, 在 <module> 中
    query = parseCommand().lower().split()
            ^^^^^^^^^^^^^^
  文件 "c:\Users\_____\.vscode\Python\AI voice\main.py", 第24行, 在 parseCommand 中
    with sr.Microphone() as source:
  文件 "C:\Users\_______\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\speech_recognition\__init__.py", 第201行, 在 __exit__ 中        
    self.stream.close()
    ^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' 对象没有属性 'close'

解决方案

问题根源

  1. AssertionError:麦克风初始化失败,导致source.stream为None,调用listen()时触发断言检查失败。
  2. AttributeError:麦克风初始化失败后,stream属性是None,with块退出时尝试调用close()方法引发错误。

修复步骤

  1. 检查麦克风权限
    确保Python程序(或运行代码的VS Code/终端)有权访问麦克风:

    • Windows:打开「设置」→「隐私和安全性」→「麦克风」,开启「允许应用访问麦克风」,并确认对应程序在列表中。
  2. 指定正确的麦克风设备
    如果有多个麦克风,默认设备可能无法正常使用,先列出所有可用设备:

    import speech_recognition as sr
    for index, name in enumerate(sr.Microphone.list_microphone_names()):
        print(f"麦克风设备 {index}: {name}")
    

    然后在代码中指定设备索引:

    with sr.Microphone(device_index=你的设备索引) as source:
    
  3. 调整speech_recognition版本
    新版本可能与Python 3.11存在兼容性问题,降级到3.8.1版本:

    pip install speechrecognition==3.8.1
    
  4. 重构代码异常处理逻辑
    将try-except块移到with块内部,避免麦克风初始化失败后触发with块退出时的错误,修改后的parseCommand函数:

    def parseCommand():
        listener = sr.Recognizer()
        print('正在监听指令')
    
        try:
            with sr.Microphone() as source:
                listener.pause_threshold = 2
                input_speech = listener.listen(source)
                
                print('正在识别语音...')
                query = listener.recognize_google(input_speech, language='en_gb')
                print(f'识别到的语音内容: {query}')
                return query
        except sr.WaitTimeoutError:
            print('等待超时,未检测到声音')
            speak('等待超时,未检测到声音')
            return 'None'
        except sr.UnknownValueError:
            print('未听清你说的内容')
            speak('未听清你说的内容')
            return 'None'
        except Exception as exception:
            print(f'发生错误: {exception}')
            speak('抱歉,运行时出现错误')
            return 'None'
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:45:03