voiceChannel.play不是函数报错:机器人语音播放代码问题排查咨询
voiceChannel.play is not a function 报错问题 Hey there, let's figure out why you're hitting this error! The core issue here is Discord.js version changes—the way we handle voice playback got a major overhaul starting from v12, and if you're using a newer version, the old voiceChannel.play() method no longer exists.
Why this error happens
In Discord.js v11 and earlier, you could directly call play() on a VoiceChannel object. But starting with v12, the playback functionality was moved to the VoiceConnection object instead. If you're running v12+ and still using the old syntax, you'll get this exact TypeError.
Fixes based on your Discord.js version
If you're using v12 or v13
You first need to join the voice channel to get a connection, then use that connection to play audio. Here's a corrected example:
// 先获取用户所在的语音频道 const voiceChannel = message.member.voice.channel; if (!voiceChannel) { return message.reply("你得先加入一个语音频道才能播放音乐哦!"); } // 连接到语音频道并播放音频 voiceChannel.join() .then(connection => { // 通过connection对象调用play方法 const dispatcher = connection.play('./path/to/your/audio.mp3'); // 可选:播放结束后自动离开频道 dispatcher.on('finish', () => { voiceChannel.leave(); }); // 捕获播放错误 dispatcher.on('error', error => { console.error('播放出错:', error); voiceChannel.leave(); }); }) .catch(error => { console.error('连接语音频道失败:', error); });
If you're using v14 or newer
Discord.js v14 split voice functionality into a separate package called @discordjs/voice. You'll need to install additional dependencies first:
npm install @discordjs/voice @discordjs/opus ffmpeg-static
Then adjust your code to use the new voice API:
const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('@discordjs/voice'); const voiceChannel = message.member.voice.channel; if (!voiceChannel) { return message.reply("请先加入语音频道!"); } // 建立语音连接 const connection = joinVoiceChannel({ channelId: voiceChannel.id, guildId: voiceChannel.guild.id, adapterCreator: voiceChannel.guild.voiceAdapterCreator, }); // 创建播放器和音频资源 const player = createAudioPlayer(); const audioResource = createAudioResource('./path/to/your/audio.mp3'); // 开始播放 player.play(audioResource); connection.subscribe(player); // 播放结束后销毁连接 player.on('stateChange', (oldState, newState) => { if (newState.status === 'idle') { connection.destroy(); } }); // 捕获播放器错误 player.on('error', error => { console.error('播放器出错:', error.message); connection.destroy(); });
Quick check to confirm your version
Run this command in your project terminal to see which Discord.js version you're using:
npm list discord.js
Once you adjust your code to match your installed version, that TypeError should disappear!
内容的提问来源于stack exchange,提问作者Facto Man

