Skip to content

错误问题汇总

1. Could not find Opus library. Make sure it is installed.

错误描述

(.venv) C:\Users\Junsen\Desktop\learning\xiaozhi-python>python xiaozhi-python.py
Traceback (most recent call last):
  File "C:\Users\Junsen\Desktop\learning\xiaozhi-python\xiaozhi-python.py", line 5, in <module>
    import opuslib
  File "C:\Users\Junsen\Desktop\learning\xiaozhi-python\.venv\lib\site-packages\opuslib\__init__.py", line 19, in <module>
    from .exceptions import OpusError  # NOQA
  File "C:\Users\Junsen\Desktop\learning\xiaozhi-python\.venv\lib\site-packages\opuslib\exceptions.py", line 10, in <module>
    import opuslib.api.info
  File "C:\Users\Junsen\Desktop\learning\xiaozhi-python\.venv\lib\site-packages\opuslib\api\__init__.py", line 20, in <module>
    raise Exception(
Exception: Could not find Opus library. Make sure it is installed.

解决方案

  1. Windows

    • 下载并安装 Opus 库。
    • 确保 opuslib 相关库正确安装。
  2. Linux/macOS

    • 运行以下命令安装 libopus:
      sh
      sudo apt-get install libopus-dev  # Ubuntu/Debian
      brew install opus                 # macOS
  3. Python 代码安装

    sh
    pip install opuslib

2. externally-managed-environment (macOS)

错误描述

(.venv) huangjunsen@huangjunsendeMac-mini py-xiaozhi % pip install -r requirements_mac.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try brew install
    xyz, where xyz is the package you are trying to
    install.
    
    If you wish to install a Python library that isn't in Homebrew,
    use a virtual environment:
    
    python3 -m venv path/to/venv
    source path/to/venv/bin/activate
    python3 -m pip install xyz
    
    If you wish to install a Python application that isn't in Homebrew,
    it may be easiest to use 'pipx install xyz', which will manage a
    virtual environment for you. You can install pipx with
    
    brew install pipx
    
    You may restore the old behavior of pip by passing
    the '--break-system-packages' flag to pip, or by adding
    'break-system-packages = true' to your pip.conf file. The latter
    will permanently disable this error.
    
    If you disable this error, we STRONGLY recommend that you additionally
    pass the '--user' flag to pip, or set 'user = true' in your pip.conf
    file. Failure to do this can result in a broken Homebrew installation.
    
    Read more about this behavior here: <https://peps.python.org/pep-0668/>

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.

解决方案

  1. 使用虚拟环境安装
    sh
    python3 -m venv my_env
    source my_env/bin/activate
    pip install -r requirements.txt
  2. 使用 `` 进行全局安装
    sh
    brew install pipx
    pipx install package_name
  3. 强制安装(不推荐)
    sh
    pip install package_name --break-system-packages

3. WebSocket连接失败: BaseEventLoop.create_connection() got an unexpected keyword argument 'extra_headers'

错误描述

python
# 建立WebSocket连接
self.websocket = await websockets.connect(
    self.WEBSOCKET_URL, 
    extra_headers=headers # 高版本这里改为 additional_headers=headers
)

解决方案

  • **新版本 **``: extra_headers 改为 additional_headers
  • **旧版本 **``: additional_headers 改为 extra_headers

4. 没有找到默认的输入/输出音频设备

错误描述

AudioCodec - ERROR - 初始化音频设备失败: [Errno -9996] Invalid input device (no default output device)
AudioCodec - WARNING - 无法初始化音频设备: [Errno -9996] Invalid input device (no default output device)

解决方案

  1. Windows:

    • 声音设置 中启用麦克风和扬声器。
  2. Linux/macOS:

    sh
    pactl list sources | grep "Name"
  3. 检查可用音频设备:

    python
    import pyaudio
    p = pyaudio.PyAudio()
    for i in range(p.get_device_count()):
        print(f"设备 {i}: {p.get_device_info_by_index(i)['name']}")
  4. 手动指定音频设备:

    python
    stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, input_device_index=0)

**5. ModuleNotFoundError: No module named '_tkinter' mac m4以下常见 **

错误描述

(.venv) apple@appledeMac-mini py-xiaozhi % python main.py

Traceback (most recent call last):
  File "/Users/apple/Desktop/py-xiaozhi/main.py", line 5, in <module>
    from src.application import Application
  File "/Users/apple/Desktop/py-xiaozhi/src/application.py", line 23, in <module>
    from src.display import gui_display, cli_display
  File "/Users/apple/Desktop/py-xiaozhi/src/display/gui_display.py", line 2, in <module>
    import tkinter as tk
  File "/opt/homebrew/Cellar/python@3.12/3.12.9/Frameworks/Python.framework/Versions/3.12/lib/python3.12/tkinter/__init__.py", line 38, in <module>
    import _tkinter  # If this fails your Python may not be configured for Tk
    ^^^^^^^^^^^^^^^
ModuleNotFoundError: No module named '_tkinter'

解决方案

  1. 安装 tcl-tk

    sh
    brew upgrade tcl-tk # 一般第一步就可以了
  2. 检查 Homebrew 的 tcl-tk 路径

    sh
    brew info tcl-tk
  3. 重新安装 Python,并链接 tcl-tk

    sh
    brew install python-tk
  4. 手动指定 Tcl/Tk 路径(如有必要)

    sh
    export PATH="/opt/homebrew/opt/tcl-tk/bin:$PATH"
    export LDFLAGS="-L/opt/homebrew/opt/tcl-tk/lib"
    export CPPFLAGS="-I/opt/homebrew/opt/tcl-tk/include"
  5. 重新创建虚拟环境

    sh
    python3 -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt

6. 导入 opuslib 失败: No module named 'pyaudioop'或'_cffi_backend'

错误描述

找到opus库文件: D:\xiaozhi\PC\py-xiaozhi-main\libs\windows\opus.dll
已添加DLL搜索路径: D:\xiaozhi\PC\py-xiaozhi-main\libs\windows
已成功加载 opus.dll: D:\xiaozhi\PC\py-xiaozhi-main\libs\windows\opus.dll
导入 opuslib 失败: No module named 'pyaudioop'
确保 opus 动态库已正确安装或位于正确的位置

找到opus库文件: D:\xiaozhi\PC\py-xiaozhi-main\libs\windows\opus.dll
已添加DLL搜索路径: D:\xiaozhi\PC\py-xiaozhi-main\libs\windows
已成功加载 opus.dll: D:\xiaozhi\PC\py-xiaozhi-main\libs\windows\opus.dll
导入 opuslib 失败: No module named '_cffi_backend'
请确保 opus 动态库已正确安装或位于正确的位置

解决方案

  1. Python版本兼容性问题

    • 这个错误通常与Python版本有关,尤其是Python 3.13版本
    • 建议使用Python 3.9-3.12版本
  2. 重新安装cffi

    sh
    pip uninstall cffi
    pip install cffi
  3. opus.dll放置

    • 确保已将opus.dll放在正确位置(项目根目录和System32目录)
    sh
    # 检查是否已复制到这些位置
    C:\Windows\System32\opus.dll
    项目根目录\opus.dll
    项目根目录\libs\windows\opus.dll
  4. 安装pyaudioop支持库

    • 对于'pyaudioop'错误,尝试降级Python版本或安装相关依赖
    sh
    pip install pyaudio

8. error: subprocess-exited-with-error(安装 numpy 失败)

错误描述

Collecting numpy==2.0.2 (from -r requirements.txt (line 8))
  Using cached https://mirrors.aliyun.com/pypi/packages/a9/75/10dd1f8116a8b796cb2c737b674e02d02e80454bda953fa7e65d8c12b016/numpy-2.0.2.tar.gz (18.9 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [21 lines of output]
      ...
      WARNING: Failed to activate VS environment: Could not parse vswhere.exe output
      ERROR: Unknown compiler(s): [['icl'], ['cl'], ['cc'], ['gcc'], ['clang'], ['clang-cl'], ['pgcc']]
      The following exception(s) were encountered:
      Running `icl ""` gave "[WinError 2] 系统找不到指定的文件。"
      Running `cl /?` gave "[WinError 2] 系统找不到指定的文件。"
      Running `cc --version` gave "[WinError 2] 系统找不到指定的文件。"
      Running `gcc --version` gave "[WinError 2] 系统找不到指定的文件。"
      Running `clang --version` gave "[WinError 2] 系统找不到指定的文件。"
      Running `clang-cl /?` gave "[WinError 2] 系统找不到指定的文件。"
      Running `pgcc --version` gave "[WinError 2] 系统找不到指定的文件。"

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

解决方案

  • 建议python版本在 3.9 - 3.12
  1. 确保 numpy 版本兼容

    numpy==2.0.2 可能存在构建问题,建议尝试安装较稳定的版本:

    sh
    pip install numpy==1.24.3

    如果你不需要特定版本,可以安装最新稳定版本:

    sh
    pip install numpy
  2. 安装编译工具

    Windows用户可能需要安装Visual C++ Build Tools:

    sh
    # 安装Microsoft C++ Build Tools
    # 下载并安装: https://visualstudio.microsoft.com/visual-cpp-build-tools/
  3. 使用预编译的轮子

    sh
    pip install --only-binary=numpy numpy

9. PaAlsaStreamComponent_BeginPolling: 假设 'ret == self->nfds' 失败 (Ubuntu ALSA错误)

错误描述

text
python: src/hostapi/alsa/pa_linux_alsa.c:3641: PaAlsaStreamComponent_BeginPolling: 假设 'ret == self->nfds' 失败。
已放弃 (核心已转储)

这是一个 PortAudio/ALSA 初始化失败的错误,表现为程序在启动音频流时崩溃。

原因分析

  1. ALSA 配置问题或音频设备权限不足
  2. PulseAudio/PipeWire 与 ALSA 冲突
  3. 系统音频设备未正确配置
  4. PortAudio 库版本不兼容

解决方案

方案 1: 检查并修复 ALSA 配置

  1. 检查音频设备是否正常

    bash
    # 列出所有音频设备
    arecord -l  # 录音设备
    aplay -l    # 播放设备

    如果命令输出 "no soundcards found",说明系统未识别到音频设备。

  2. 测试音频设备

    bash
    # 测试录音(按 Ctrl+C 停止)
    arecord -f S16_LE -r 16000 -c 1 test.wav
    
    # 测试播放
    aplay test.wav
  3. 检查 ALSA 工具是否安装

    bash
    sudo apt-get update
    sudo apt-get install -y alsa-utils alsa-base

方案 2: 使用 PulseAudio (推荐)

ALSA 直接访问硬件设备可能存在兼容性问题,推荐通过 PulseAudio 作为音频服务器:

bash
# 安装 PulseAudio
sudo apt-get install -y pulseaudio pulseaudio-utils

# 启动 PulseAudio
pulseaudio --start

# 检查 PulseAudio 是否运行
pactl info

# 列出音频设备
pactl list sources | grep "Name"    # 输入设备
pactl list sinks | grep "Name"      # 输出设备

如果 PulseAudio 工作正常,Python sounddevice 会自动使用 PulseAudio 而不是直接访问 ALSA。

方案 3: 配置 ALSA 使用 PulseAudio

创建或编辑 ~/.asoundrc 文件:

bash
nano ~/.asoundrc

添加以下内容:

text
pcm.!default {
    type pulse
}

ctl.!default {
    type pulse
}

然后重启音频服务:

bash
pulseaudio --kill
pulseaudio --start

方案 4: 添加用户到 audio 组

bash
# 将当前用户添加到 audio 组
sudo usermod -a -G audio $USER

# 重新登录系统生效,或使用以下命令临时生效
newgrp audio

# 检查用户组
groups

方案 5: 重新安装 PortAudio 和 sounddevice

bash
# 卸载 Python 音频库
pip uninstall sounddevice pyaudio -y

# 重新安装系统依赖
sudo apt-get remove --purge portaudio19-dev libportaudio2
sudo apt-get update
sudo apt-get install -y portaudio19-dev libportaudio2 libasound2-dev

# 重新安装 Python 库
pip install sounddevice

方案 6: 检查并禁用冲突的音频服务

某些情况下,多个音频服务可能冲突:

bash
# 检查运行的音频服务
ps aux | grep -E "pulse|pipewire|jack"

# 如果同时运行了 PipeWire 和 PulseAudio,建议只保留一个
# Ubuntu 22.04+ 默认使用 PipeWire,但通过 pipewire-pulse 兼容 PulseAudio

# 检查 PipeWire 状态
systemctl --user status pipewire pipewire-pulse

方案 7: 使用虚拟音频设备 (仅用于测试)

如果硬件设备有问题,可以创建虚拟音频设备进行测试:

bash
# 加载虚拟音频模块
pactl load-module module-null-sink sink_name=virtual_speaker
pactl load-module module-virtual-source source_name=virtual_mic

# 查看虚拟设备
pactl list sources short
pactl list sinks short

验证修复

运行以下 Python 代码测试音频设备是否正常:

python
import sounddevice as sd

# 列出所有设备
print(sd.query_devices())

# 测试录音和播放
import numpy as np

# 录制 2 秒音频
print("Recording...")
audio = sd.rec(int(2 * 16000), samplerate=16000, channels=1, dtype=np.int16)
sd.wait()
print("Recording finished")

# 播放录制的音频
print("Playing...")
sd.play(audio, samplerate=16000)
sd.wait()
print("Playing finished")

如果上述代码运行成功,说明音频设备配置正确。

注意事项

  1. Ubuntu 20.04/22.04 默认使用不同的音频系统:

    • Ubuntu 20.04: 主要使用 PulseAudio
    • Ubuntu 22.04+: 使用 PipeWire (兼容 PulseAudio)
  2. 远程/无头服务器: 如果是无显示器的服务器环境,确保音频服务正常启动:

    bash
    # 检查音频服务
    systemctl --user status pulseaudio
  3. Docker/容器环境: 容器内需要映射宿主机的音频设备:

    bash
    docker run --device /dev/snd ...
  4. 权限问题: 确保 /dev/snd/ 目录有正确的权限:

    bash
    ls -l /dev/snd/