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
相关产品推荐
相关产品推荐

