You need to enable JavaScript to run this app. discord.py机器人在VC播放长音乐时报OSError:Errno9 Bad file descriptor错
优惠活动
大模型
产品
解决方案
定价
更多

discord.py机器人在VC播放长音乐时报OSError:Errno9 Bad file descriptor错

长时长音频播放触发Errno 9错误的排查与修复

问题根因

  • 当前实现没有适配长音频的读取时序,短文件下载、转码流程快,不会出现句柄未释放的问题;5分钟以上的文件需要更长的下载、转码耗时,很容易碰到临时文件的句柄还被转码进程占用时就被重命名/读取的情况,触发文件描述符错误
  • 默认的FFmpegPCMAudio没有设置足够的读取队列和重连参数,树莓派低性能CPU读取大文件时容易出现底层IO超时,导致已经打开的文件描述符被系统回收,后续读写时就抛出Errno 9错误
  • 反复调用os.chdir切换工作目录,多指令并发时容易出现路径偏移,找不到目标文件也会触发同类错误

针对性修复代码

把原有播放逻辑替换为下面的实现,规避上述问题:

elif message.content.casefold().startswith("rachel play"):
    base_dir = "/home/pi/rachel"
    song_path = os.path.join(base_dir, "song.mp3")
    # 清理旧的缓存文件,带异常捕获
    if os.path.isfile(song_path):
        try:
            os.remove(song_path)
        except PermissionError:
            await message.channel.send("Warte")
            return
    # 校验语音连接状态,未连接时自动加入用户所在频道
    voice = discord.utils.get(self.bot.voice_clients, guild=message.guild)
    if not voice:
        if not message.author.voice:
            await message.channel.send("Du musst erst in einem Sprachchannel sein")
            return
        voice = await message.author.voice.channel.connect()
    # 提取播放链接
    parts = message.content.split()
    url = parts[-1]
    ydl_opts = {
        'format': 'bestaudio/best',
        'outtmpl': os.path.join(base_dir, '%(unique_id)s.%(ext)s'),
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
        'quiet': True,
        'noplaylist': True
    }
    # 等待下载和转码完全完成后再获取文件路径
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=True)
        temp_file = ydl.prepare_filename(info)
        final_mp3 = os.path.splitext(temp_file)[0] + ".mp3"
    # 直接按已知路径重命名,不需要遍历目录找文件
    os.rename(final_mp3, song_path)
    # 给FFmpeg增加长文件适配参数
    ffmpeg_config = {
        'before_options': '-thread_queue_size 8192 -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 10',
        'options': '-vn -ar 44100 -ac 2 -b:a 192k'
    }
    audio_source = discord.FFmpegPCMAudio(song_path, **ffmpeg_config)
    voice.play(audio_source)

额外排查注意事项

  • 检查树莓派的系统文件描述符限额:执行ulimit -n查看当前限额,如果数值低于2048,需要在运行机器人的系统服务配置里调高限额,避免长播放时累积的句柄被系统强制回收
  • 建议替换已停止维护的youtube-dl为yt-dlp,新版本对大文件的转码进程管理更稳定,不会出现转码完成后句柄未及时释放的问题
  • 不要在播放长音频的过程中频繁触发新的播放指令,避免ffmpeg进程和文件清理逻辑抢占同一个文件的访问权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 11:36:02