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

Discord.js v12.5自制音乐命令可加入语音频道但无法播放音乐怎么解决

Discord.js v12 音乐播放故障修复

问题核心错误点

  • Discord.js v12 已废弃VoiceConnection.playStream()方法,需改用play()方法传入音频流
  • 代码中引用的streamOptions变量未提前定义,会触发未定义报错
  • 缺少语音播放必需的底层依赖,也会导致无声音输出

修正后可运行代码

const ytdl = require('ytdl-core');
// 确保顶部已经导入ytdl,遗漏导入也会导致运行失败

client.on('message', message => {
  if (message.content.startsWith('music plz')) {
    const voiceChannel = message.member.voice.channel;
    if (!voiceChannel) {
      return message.reply(`Wow what a scrub, join a Voice Channel first`);
    }
    voiceChannel.join()
      .then(connection => {
        const stream = ytdl('https://www.youtube.com/watch?v=dQw4w9WgXcQ', { filter: 'audioonly' });
        // 定义播放配置,可按需调整音量等参数
        const streamOptions = { volume: 0.7 };
        const dispatcher = connection.play(stream, streamOptions);
        
        // 新增错误监听方便排查后续问题
        dispatcher.on('error', error => {
          console.error('播放错误: ', error);
          voiceChannel.leave();
        });
        
        // 播放结束自动退出频道
        dispatcher.on('finish', () => {
          voiceChannel.leave();
        });
      })
      .catch(err => console.error('加入语音频道失败: ', err));
  }
});

前置依赖检查

运行前执行以下命令安装所有必需依赖:
npm install ytdl-core @discordjs/opus ffmpeg-static

同时确认你的机器人已经在对应语音频道被授予CONNECT和SPEAK权限,权限不足也会导致无声音输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:27:04