Tổng hợp lỗi thường gặp
1. Could not find Opus library. Make sure it is installed.
Mô tả lỗi
(.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.Giải pháp
Windows
- Tải xuống và cài đặt thư viện Opus.
- Đảm bảo các thư viện liên quan đến
opuslibđã được cài đặt đúng cách.
Linux/macOS
- Chạy lệnh sau để cài đặt
libopus:shsudo apt-get install libopus-dev # Ubuntu/Debian brew install opus # macOS
- Chạy lệnh sau để cài đặt
Cài đặt gói Python
shpip install opuslib
2. externally-managed-environment (macOS)
Mô tả lỗi
(.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.Giải pháp
- Cài đặt trong môi trường ảosh
python3 -m venv my_env source my_env/bin/activate pip install -r requirements.txt - Sử dụng
pipxđể cài đặt toàn cụcshbrew install pipx pipx install package_name - Ép cài đặt (không khuyến nghị)sh
pip install package_name --break-system-packages
3. WebSocket连接失败: BaseEventLoop.create_connection() got an unexpected keyword argument 'extra_headers'
Mô tả lỗi
# Thiết lập kết nối WebSocket
self.websocket = await websockets.connect(
self.WEBSOCKET_URL,
extra_headers=headers # Ở phiên bản cao hơn đổi thành additional_headers=headers
)Giải pháp
- Phiên bản
websocketsmới: đổiextra_headersthànhadditional_headers. - Phiên bản
websocketscũ: đổiadditional_headersthànhextra_headers.
4. Không tìm thấy thiết bị âm thanh đầu vào/đầu ra mặc định
Mô tả lỗi
AudioCodec - ERROR - 初始化音频设备失败: [Errno -9996] Invalid input device (no default output device)
AudioCodec - WARNING - 无法初始化音频设备: [Errno -9996] Invalid input device (no default output device)Giải pháp
Windows:
- Vào Cài đặt âm thanh (Sound Settings) để bật micro và loa.
Linux/macOS:
shpactl list sources | grep "Name"Kiểm tra các thiết bị âm thanh khả dụng:
pythonimport pyaudio p = pyaudio.PyAudio() for i in range(p.get_device_count()): print(f"Thiết bị {i}: {p.get_device_info_by_index(i)['name']}")Chỉ định thủ công thiết bị âm thanh:
pythonstream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, input_device_index=0)
5. ModuleNotFoundError: No module named '_tkinter' (thường gặp trên Mac dưới M4)
Mô tả lỗi
(.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'Giải pháp
Cài đặt
tcl-tkshbrew upgrade tcl-tk # Thông thường chỉ cần bước đầu tiên là đủKiểm tra đường dẫn
tcl-tkcủa Homebrewshbrew info tcl-tkCài đặt lại Python và liên kết với
tcl-tkshbrew install python-tkChỉ định thủ công đường dẫn
Tcl/Tk(nếu cần)shexport 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"Tạo lại môi trường ảo
shpython3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt
6. Lỗi nhập opuslib: No module named 'pyaudioop' hoặc '_cffi_backend'
Mô tả lỗi
找到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 动态库已正确安装或位于正确的位置Hoặc:
找到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 动态库已正确安装或位于正确的位置Giải pháp
Vấn đề tương thích phiên bản Python
- Lỗi này thường liên quan đến phiên bản Python, đặc biệt là Python 3.13
- Khuyến nghị sử dụng Python 3.9–3.12
Cài đặt lại
cffishpip uninstall cffi pip install cffiVị trí đặt tệp
opus.dll- Đảm bảo đã đặt
opus.dllđúng vị trí (thư mục gốc dự án và thư mục System32)
sh# Kiểm tra xem đã sao chép vào các vị trí sau chưa C:\Windows\System32\opus.dll <thư_mục_gốc_dự_án>\opus.dll <thư_mục_gốc_dự_án>\libs\windows\opus.dll- Đảm bảo đã đặt
Cài đặt thư viện hỗ trợ
pyaudioop- Đối với lỗi
'pyaudioop', hãy thử hạ phiên bản Python hoặc cài đặt gói phụ thuộc liên quan
shpip install pyaudio- Đối với lỗi
8. error: subprocess-exited-with-error (lỗi khi cài đặt numpy)
Mô tả lỗi
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.Giải pháp
- Khuyến nghị dùng phiên bản Python từ 3.9 đến 3.12
Đảm bảo phiên bản
numpytương thíchnumpy==2.0.2có thể gặp lỗi khi biên dịch; khuyến nghị thử cài đặt phiên bản ổn định hơn:shpip install numpy==1.24.3Nếu không yêu cầu phiên bản cụ thể, có thể cài đặt phiên bản ổn định mới nhất:
shpip install numpyCài đặt công cụ biên dịch
Người dùng Windows có thể cần cài đặt Visual C++ Build Tools:
sh# Cài đặt Microsoft C++ Build Tools # Tải xuống và cài đặt tại: https://visualstudio.microsoft.com/visual-cpp-build-tools/Sử dụng gói wheel đã biên dịch sẵn
shpip install --only-binary=numpy numpy
9. PaAlsaStreamComponent_BeginPolling: Assertion 'ret == self->nfds' failed (Lỗi ALSA trên Ubuntu)
Mô tả lỗi
python: src/hostapi/alsa/pa_linux_alsa.c:3641: PaAlsaStreamComponent_BeginPolling: 假设 'ret == self->nfds' 失败。
已放弃 (核心已转储)Đây là lỗi khởi tạo PortAudio/ALSA thất bại, biểu hiện là chương trình bị thoát đột ngột (crash) khi khởi động luồng âm thanh.
Phân tích nguyên nhân
- Lỗi cấu hình ALSA hoặc thiếu quyền truy cập thiết bị âm thanh
- Xung đột giữa PulseAudio/PipeWire và ALSA
- Thiết bị âm thanh hệ thống chưa được cấu hình đúng
- Phiên bản thư viện PortAudio không tương thích
Giải pháp
Cách 1: Kiểm tra và sửa cấu hình ALSA
Kiểm tra thiết bị âm thanh có hoạt động bình thường không
bash# Liệt kê toàn bộ thiết bị âm thanh arecord -l # Thiết bị thu âm aplay -l # Thiết bị phát âm thanhNếu lệnh xuất ra
"no soundcards found", nghĩa là hệ thống chưa nhận diện được thiết bị âm thanh.Kiểm thử thiết bị âm thanh
bash# Kiểm thử thu âm (nhấn Ctrl+C để dừng) arecord -f S16_LE -r 16000 -c 1 test.wav # Kiểm thử phát lại aplay test.wavKiểm tra các công cụ ALSA đã được cài đặt chưa
bashsudo apt-get update sudo apt-get install -y alsa-utils alsa-base
Cách 2: Sử dụng PulseAudio (khuyến nghị)
Việc ALSA truy cập trực tiếp vào thiết bị phần cứng có thể gây lỗi tương thích; khuyến nghị dùng PulseAudio làm máy chủ âm thanh trung gian:
# Cài đặt PulseAudio
sudo apt-get install -y pulseaudio pulseaudio-utils
# Khởi động PulseAudio
pulseaudio --start
# Kiểm tra PulseAudio có đang chạy không
pactl info
# Liệt kê thiết bị âm thanh
pactl list sources | grep "Name" # Thiết bị đầu vào
pactl list sinks | grep "Name" # Thiết bị đầu raNếu PulseAudio hoạt động bình thường, sounddevice của Python sẽ tự động sử dụng PulseAudio thay vì truy cập trực tiếp vào ALSA.
Cách 3: Cấu hình ALSA dùng PulseAudio
Tạo hoặc chỉnh sửa tệp ~/.asoundrc:
nano ~/.asoundrcThêm nội dung sau:
pcm.!default {
type pulse
}
ctl.!default {
type pulse
}Sau đó khởi động lại dịch vụ âm thanh:
pulseaudio --kill
pulseaudio --startCách 4: Thêm người dùng vào nhóm audio
# Thêm người dùng hiện tại vào nhóm audio
sudo usermod -a -G audio $USER
# Đăng nhập lại hệ thống để có hiệu lực, hoặc dùng lệnh sau để áp dụng tạm thời
newgrp audio
# Kiểm tra danh sách nhóm của người dùng
groupsCách 5: Cài đặt lại PortAudio và sounddevice
# Gỡ các thư viện âm thanh Python
pip uninstall sounddevice pyaudio -y
# Cài đặt lại gói phụ thuộc hệ thống
sudo apt-get remove --purge portaudio19-dev libportaudio2
sudo apt-get update
sudo apt-get install -y portaudio19-dev libportaudio2 libasound2-dev
# Cài đặt lại thư viện Python
pip install sounddeviceCách 6: Kiểm tra và tắt các dịch vụ âm thanh xung đột
Trong một số trường hợp, nhiều dịch vụ âm thanh chạy đồng thời có thể gây xung đột:
# Kiểm tra các dịch vụ âm thanh đang chạy
ps aux | grep -E "pulse|pipewire|jack"
# Nếu cả PipeWire và PulseAudio đang chạy cùng lúc, nên chỉ giữ lại một dịch vụ
# Ubuntu 22.04+ mặc định dùng PipeWire và tương thích với PulseAudio thông qua pipewire-pulse
# Kiểm tra trạng thái PipeWire
systemctl --user status pipewire pipewire-pulseCách 7: Sử dụng thiết bị âm thanh ảo (chỉ dùng cho kiểm thử)
Nếu thiết bị phần cứng gặp sự cố, bạn có thể tạo thiết bị âm thanh ảo để kiểm thử:
# Nạp mô-đun âm thanh ảo
pactl load-module module-null-sink sink_name=virtual_speaker
pactl load-module module-virtual-source source_name=virtual_mic
# Xem các thiết bị ảo
pactl list sources short
pactl list sinks shortXác minh đã khắc phục
Chạy đoạn mã Python sau để kiểm tra thiết bị âm thanh có hoạt động bình thường hay không:
import sounddevice as sd
# Liệt kê tất cả thiết bị
print(sd.query_devices())
# Kiểm thử thu âm và phát lại
import numpy as np
# Thu 2 giây âm thanh
print("Recording...")
audio = sd.rec(int(2 * 16000), samplerate=16000, channels=1, dtype=np.int16)
sd.wait()
print("Recording finished")
# Phát lại đoạn âm thanh vừa thu
print("Playing...")
sd.play(audio, samplerate=16000)
sd.wait()
print("Playing finished")Nếu đoạn mã trên chạy thành công, thiết bị âm thanh đã được cấu hình đúng.
Lưu ý
Ubuntu 20.04/22.04 mặc định sử dụng hệ thống âm thanh khác nhau:
- Ubuntu 20.04: Chủ yếu dùng PulseAudio
- Ubuntu 22.04+: Dùng PipeWire (tương thích với PulseAudio)
Máy chủ từ xa / không màn hình (headless): Trong môi trường máy chủ không có màn hình, hãy đảm bảo dịch vụ âm thanh đã được khởi động bình thường:
bash# Kiểm tra dịch vụ âm thanh systemctl --user status pulseaudioMôi trường Docker/Container: Cần ánh xạ thiết bị âm thanh của máy chủ vào bên trong container:
bashdocker run --device /dev/snd ...Vấn đề phân quyền: Đảm bảo thư mục
/dev/snd/có quyền truy cập phù hợp:bashls -l /dev/snd/