HashtagForgotName
HashtagForgotName

Reputation: 671

First song is playing fine but second song doesn't with no errors in discord.js

Im trying to make a queue system in discord.js for my bot. When I add 2 songs to test with the command it puts them in the queue like this:

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

The first songs plays out fine and works but then when it comes to the transitions the sounds just stops. The console returns no error, probably there's a logical error, but I can not figure out where it is going wrong.

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' }));
 }

I just don't understand how the first song plays fine without any problems but when it comes to the second song the bot just stops but there is no error in the console.

Upvotes: 2

Views: 46

Answers (1)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23160

Array.shift() in JavaScript mutates the array. It removes the first element from an array and returns that removed element.

When you assign the return value from the shift() in your play() method, you update this.playQueue and set it to the removed element.

At this moment, this.playQueue is no longer an array but a string, and when you call ytdl(this.playQueue[0], ...) the second time, you call the function with the first character of that string (h from https://...) instead of the link.

As shift() mutates the array, you don't need to reassign it:

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' }));
 }

Upvotes: 1

Related Questions