Discord.js 语音播放器的问题

Posted

技术标签:

【中文标题】Discord.js 语音播放器的问题【英文标题】:Issue with Discord.js voice player 【发布时间】:2021-11-16 12:46:57 【问题描述】:

我一直在尝试在 discord.js 上为我的 DnD 组设置一个简单的音乐机器人,我可以让它提取命令、加入服务器和搜索 YouTube 视频,但我无法让它在语音频道上播放,给我一个 *Cannot read properties of undefined (reading 'once')。我刚刚开始编写代码,这完全让我难过。

这是播放代码和index.js 文件。我可能遗漏了一些明显的问题,我们将不胜感激!

播放代码:

const ytdl = require('ytdl-core');

const ytSearch = require('yt-search');

const 
  createAudioPlayer,
  createAudioResource,
  AudioPlayer,
  VoiceConnection,
  joinVoiceChannel
 = require('@discordjs/voice');
const  VoiceChannel  = require('discord.js');

const player = createAudioPlayer();

const resource = createAudioResource('ytdl');

module.exports = 
    name: 'play',
    description: 'Plays video',
    async execute(message, args) 
        const voiceChannel = message.member.voice.channel;
        if (!voiceChannel) return message.channel.send('I cannot enter the tavern!');
        const permissions = voiceChannel.permissionsFor(message.client.user);
        if (!permissions.has('CONNECT')) return message.channel.send('I cannot reach you!');
        if (!permissions.has('SPEAK')) return message.channel.send('I cannot hear you!');
        if (!args.length) return message.channel.send('You need to tell me the song!');
        const videoFinder = async (query) => 
          const videoResult = await ytSearch(query);
          return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
        
        const video = await videoFinder(args.join(' '));
        if(video)
            const stream = ytdl(video.url, filter: 'audioonly');
           player.play ( stream,  seek: 0, volume: .5 )
          ;
          connection.subscribe(player);
         await message.reply(`:thumbsup: Now Playing ***$video.title***`)
         else 
         message.channel.send(`No video results found`);
        
    
    

index.js:

console.clear();

const fs = require('fs');

const  Client, Collection, Intents, DiscordAPIError  = require('discord.js');
const  prefix, token  = require('./config.json');

const client = new Client( intents: [32767] );

client.commands = new Collection();
client.slashCommands = new Collection();

const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) 
    const command = require(`./commands/$file`);
    client.commands.set(command.data.name, command);


client.once('ready', () => 
    console.log('The Nymph awakens.');
);


client.on('message', message => 
    if(!message.content.startsWith(prefix) || message.author.bot) return;
  
    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();


    if(command === "ping") 
        client.commands.get('ping').execute(message, args); else if (command === "play") 
            client.commands.get('play').execute(message, args);
           else if (command === "leave") 
            client.commands.get('leave').execute(message, args);
          
        
         
         if(message.content === '!join') 
            const voiceChannel = message.member.voice.channel;
           if (!voiceChannel) return message.channel.send('I cannot enter the tavern!');
           joinVoiceChannel(
             channelId: message.member.voice.channel.id,
             guildId: message.guild.id,
              adapterCreator: message.guild.voiceAdapterCreator
                  )
              
          
        
        
        
          if(command === "hello") 
            message.channel.send('You wish to speak?');
           else if (command == 'goodbye') 
            message.channel.send("See you on the morrow.");
           else if (command == 'hey') 
            message.channel.send("I wish not for hay."); 
           else if (command == 'hi') 
            message.channel.send("No, I am low to the ground.");
           else if (command == 'bye') 
            message.channel.send("Farewell.");
           else if (command == 'Status') 
            message.channel.send("I fare well.");
           else if (command == 'dnd time') 
            message.channel.send("I am oft unawares.");
           else if (command == 'wake') 
            message.channel.send("Why do you rouse me?");
           else if (command == 'intro') 
            message.channel.send("I am a nymph named Aria. I help adventurers in their quest to be immersed in their work.");
          
      

    if (!command) return;

    
    
);

client.login(token);

编辑:我相信错误来自这行特定的代码,这就是发生的错误。

const video = await videoFinder(args.join(' '));
        if(video)
            const stream = ytdl(video.url, filter: 'audioonly');
           player.play ( stream,  seek: 0, volume: .5 )
          ;
          connection.subscribe(player);
         await message.reply(`:thumbsup: Now Playing ***$video.title***`)
         else 
         message.channel.send(`No video results found`);

“TypeError:无法读取未定义的属性(读取'一次') 在 AudioPlayer.play (C:\Users\"我的用户名"\Documents\DungeonNymph\node_modules@discordjs\voice\dist\audio\AudioPlayer.js:221:29) 在 Object.execute (C:\Users\"我的用户名"\Documents\DungeonNymph\Commands\play.js:38:19) 在 processTicksAndRejections (node:internal/process/task_queues:96:5)"

【问题讨论】:

嗨,欢迎来到 ***!您能否请edit您的问题并包含有关错误发生位置的错误/详细信息的堆栈跟踪?如果错误直接发生在您发布的代码中,则唯一的位置是client.once('ready', () => ,它不应该抛出该错误,因为client 已经用const client = new Client(...) 定义。 谢谢!感谢格式化方面的帮助,我添加了堆栈跟踪以帮助找到代码的这个损坏部分。 【参考方案1】:

问题在于AudioPlayer#play 接受AudioResource,而不是流。

使用createAudioResource 使用 ytdl 流创建音频资源:

const stream = ytdl(video.url,  filter: 'audioonly' );
const resource = createAudioResource(stream,  inlineVolume: true );
resource.volume.setVolume(0.5);
player.play(resource);

如果inlineVolume 设置为true(默认false),resource.volume 将是prism-media VolumeTransformer,您可以使用它来设置流的音量。

createAudioResource 选项的文档和选项未显示在文档网站 (#211) 上,但您可以在源代码中找到相关文档 cmets:

createAudioResource CreateAudioResourceOptions

我建议查看@discordjs/voice 存储库中的music bot example,了解如何使用该库。

【讨论】:

以上是关于Discord.js 语音播放器的问题的主要内容,如果未能解决你的问题,请参考以下文章

Discord.js v13,@discordjs/voice 播放音乐命令

从 twitch bot 调用 Discord.js 音乐问题找到语音频道

discord.js 不播放音频文件

Discord 机器人不离开语音频道

Discord.js 播放音频文件错误

Discord Bot 不播放音频 discord.js v13