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

树莓派4B上Pygame调用ALSA音频设备报错Unknown error 524求助

树莓派4B上Pygame初始化ALSA音频设备报错(错误524)问题

我在树莓派4B上开发语音功能,流程是用pyttsx3将文本转换为.wav文件,再通过Pygame播放(因pyttsx3内置播放功能报错难以排查,故采用此方案)。该功能在Windows系统可正常运行,但在树莓派上触发ALSA相关错误:pygame.error: ALSA: Couldn't open audio device: Unknown error 524,尝试多种论坛方案均未解决,相关代码及完整报错信息如下:

功能代码

'''File to utilise the speaker system'''
import pyttsx3 
import pygame
import os

pygame.init()
mix = pygame.mixer
mix.init()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[12].id)
engine.setProperty('rate', 155)


# Function to convert text to
# speech
def SpeakText(command):
    # Initialize the engine
    engine.save_to_file(command, "Words.wav") 
    engine.runAndWait()
    mix.music.load("Words.wav")
    mix.music.play()
    while pygame.mixer.music.get_busy() == True:
        continue
    mix.music.unload()
    if os.path.exists("Words.wav"):
        os.remove("Words.wav")
    else:
        print("The file does not exist")

完整报错信息

pygame 2.1.2 (SDL 2.26.5, Python 3.11.2)
Hello from the pygame community. https://ww.pygame.org/contribute.html
Traceback (most recent call last):
   File "/home/user/Project-Sigmund/main.py", line 4, in <module>
     import inputOutput #name of file
   File "/home/user/Project-Sigmund/inputOutput.py", line 7, in <module>
     mix.init()
pygame.error: ALSA: Couldn't open audio device: Unknown error 524

排查与解决步骤

  • 检查音频设备权限
    将当前用户加入audio组,获取音频设备访问权限:

    sudo usermod -aG audio $USER
    

    重启树莓派后重新运行代码测试。

  • 指定Pygame音频参数初始化
    修改mix.init()的参数,明确采样率、通道等配置,避免自动适配出错:

    mix.init(frequency=16000, size=-16, channels=1, buffer=2048)
    

    或直接指定ALSA设备:

    os.environ['SDL_AUDIODRIVER'] = 'alsa'
    os.environ['SDL_AUDIODEV'] = 'plughw:0,0'
    mix.init()
    
  • 验证ALSA配置与设备
    用命令查看可用音频设备列表:

    aplay -l
    

    编辑ALSA配置文件/usr/share/alsa/alsa.conf,确保默认设备编号与实际一致:

    defaults.ctl.card 0
    defaults.pcm.card 0
    
  • 替换Pygame为其他音频播放库
    若Pygame的ALSA适配始终有问题,可换用simpleaudio直接播放wav文件:

    import simpleaudio as sa
    
    def play_wav(file_path):
        wave_obj = sa.WaveObject.from_wave_file(file_path)
        play_obj = wave_obj.play()
        play_obj.wait_done()
    

    安装依赖:

    pip install simpleaudio
    
  • 更新系统与依赖库
    升级树莓派系统及相关音频组件:

    sudo apt update && sudo apt upgrade -y
    sudo apt install alsa-utils pulseaudio
    pip install --upgrade pygame pyttsx3
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 01:40:05