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

使用AudioPlayer库播放音频失败,错误代码289求助

解决AudioPlayer库播放音频错误码289的问题

问题重现

使用AudioPlayer库实现音频播放时触发错误:

Failed to play "...\out.wav", code 289

相关代码及库内报错逻辑如下:

业务代码

def play_file(file: str, playback: bool):
    global playback_device

    path = os.path.join(os.getcwd(), file)

    if not (os.path.exists(path)):
        print(f'No file found at path \'{path}\'')
        print('Cannot play file.')
        return

    mixer.music.load(file)
    mixer.music.play()

    if playback:
        if playback_device is not None:
            playback_device.close()
        try:
            playback_device = AudioPlayer(file)
            playback_device.play()
        except audioplayer.abstractaudioplayer.AudioPlayerError as e:
            print('Failed to start playback')
            print(e)

库内报错逻辑(已修改显示错误码)

def _load_player(self):
    ret = self._mciSendString('open "{}" type mpegvideo alias {}'.format(self._filename, self._alias))
    if ret > 0:
        raise AudioPlayerError( 'Failed to play "{}", code {}'.format(self.fullfilename, ret))
    return ret

别名生成逻辑为"A{}".format(id(self)),此前代码放在其他函数中可正常运行,当前场景下出现上述错误。

错误原因分析

错误码289对应MCI(媒体控制接口)的别名已被占用错误,可能的触发原因:

  1. 全局变量playback_device的旧实例调用close()后,MCI别名未被完全释放
  2. 同时使用mixer.music(如pygame mixer)和AudioPlayer,抢占音频资源或MCI接口
  3. 别名生成依赖id(self),多次创建实例时可能出现重复(极端场景下)
  4. 传递给AudioPlayer的是相对路径,MCI解析路径时出现异常

解决方案

1. 确保旧实例资源完全释放

在关闭旧实例后,手动发送MCI命令释放别名,避免残留占用:

if playback_device is not None:
    playback_device.close()
    # 手动调用MCI命令释放别名
    from audioplayer import _mciSendString
    _mciSendString(f'close {playback_device._alias}')
    playback_device = None

2. 避免多音频库资源冲突

如果不需要同时使用mixer.music,直接移除相关代码;若必须使用,先释放mixer资源:

# 在初始化AudioPlayer前添加
mixer.music.stop()
mixer.music.unload()

3. 自定义唯一别名

替换默认的id(self)别名生成逻辑,用递增计数器保证唯一性:

# 全局维护别名计数器
alias_counter = 0

def play_file(file: str, playback: bool):
    global playback_device, alias_counter
    # ... 其他代码 ...
    if playback:
        # ... 关闭旧实例逻辑 ...
        try:
            alias_counter += 1
            playback_device = AudioPlayer(path)  # 使用绝对路径
            playback_device._alias = f"AUDIO_PLAYER_{alias_counter}"
            playback_device._load_player()  # 重新加载播放器
            playback_device.play()
        except audioplayer.abstractaudioplayer.AudioPlayerError as e:
            print('Failed to start playback')
            print(e)

4. 使用绝对路径传递文件

确保传递给AudioPlayer的是绝对路径,避免MCI解析相对路径出错:

# 替换原代码中的AudioPlayer(file)为
playback_device = AudioPlayer(path)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:32:35