【问题标题】:First song is playing fine but second song doesn't with no errors in discord.js第一首歌曲播放良好,但第二首歌曲在 discord.js 中没有错误
【发布时间】:2021-04-20 00:35:47
【问题描述】:

我正在尝试在 discord.js 中为我的机器人创建一个队列系统。当我使用命令添加 2 首歌曲进行测试时,它会将它们放入队列中,如下所示:

[
   'https://www.youtube.com/watch?v=Jgv7qhDLPhg&ab_channel=BruhSoundEffects',
   'https://www.youtube.com/watch?v=Jgv7qhDLPhg&ab_channel=BruhSoundEffects'
]

第一首歌曲播放效果很好并且可以正常工作,但是当涉及到过渡时,声音就停止了。控制台没有返回错误,可能是逻辑错误,但我不知道哪里出错了。

module.exports = class Youtube {

constructor(){
  this.playQueue = [];
  this.dispatcher = null;
}

playYoutubeMusic(channel, message, args, volume = 0.2) {
  if(!args[0]) return message.channel.send('no link provided');
  if(!this.validYtLink(args[0])) return message.channel.send('Invalid yt link');

  console.log(this.playQueue.length);

  const _this = this;
  if(this.playQueue.length == 0){
      this.playQueue.push(args[0]);
      console.log(this.playQueue.length);
      channel.join().then(connection => {
        this.play(false, connection);
        this.dispatcher.setVolume(volume);

        this.dispatcher.on("finish", function () {
            console.log("test");
            console.log(_this.playQueue);
            if (_this.playQueue.length != 0) {
              _this.play(true, connection);
            }
            else connection.disconnect();
        });
      });
  } else {
    this.playQueue.push(args[0]);
    console.log(this.playQueue);
  }
}

play(shift = false, connection){
    console.log("test");
    if(shift) this.playQueue = this.playQueue.shift();
    this.dispatcher = connection.play(ytdl(this.playQueue[0], { quality: 'highestaudio' }));
 }
  • channel 来自const channel = client.channels.cache.get("626133529130172432");
  • message 来自client.on("message", function(message)
  • args 在这种情况下是链接

我只是不明白第一首歌曲如何正常播放而没有任何问题,但是当谈到第二首歌曲时,机器人只是停止了,但控制台中没有错误。

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    Array.shift() 在 JavaScript 中改变数组。它从数组中删除第一个元素并返回删除的元素。

    当您在 play() 方法中从 shift() 分配返回值时,您会更新 this.playQueue 并将其设置为已删除的元素。

    此时this.playQueue不再是一个数组而是一个字符串,当你第二次调用ytdl(this.playQueue[0], ...)时,你调用的是那个字符串的第一个字符的函数(h来自https://...)而不是链接。

    由于shift() 改变了数组,您不需要重新分配它:

    play(shift = false, connection){
      console.log("test");
    
      if(shift) {
        // shift() updates this.playQueue, no need to reassign
        this.playQueue.shift();
      }
    
      this.dispatcher = connection.play(ytdl(this.playQueue[0], { quality: 'highestaudio' }));
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多