0

So I have this script that randomises through a passed object. It works fine.

But I added a feature that checks if the song that was played before is the same as the song that will be played in the function, and if so, making it not the same. This doesn't work.

I don't know why, but for some reason, the same songs can play after each other and it's pretty annoying.

Here's the part of the script that randomizes:

const musicSelect = function(selectedObject) {
  const rand = Math.floor(Math.random() * selectedObject.length);
  if (selectedObject[rand].url != playingSong) {
    source.src = selectedObject[rand].url;
    playingSong = source.src;
    console.log("Playing " + selectedObject[rand].name);
    document.getElementById("Title").innerHTML = "Playing: " + selectedObject[rand].name;
    /* Making it that its impossible to get the same music consecutive times */
  } else {
    /* Check if the song is the last song in the object, 
    if so then pick a new song another way to prevent error */

    if (selectedObject[rand] == selectedObject.length) {
      source.src = selectedObject[rand - 1].url;
      playingSong = source.src;
      console.log("Playing " + selectedObject[rand - 1]);
      document.getElementById("Title").innerHTML = "Playing: " + selectedObject[rand - 1];
    } else {
      source.src = selectedObject[rand + 1].url;
      playingSong = source.src;
      console.log("Playing " + selectedObject[rand + 1]);
      document.getElementById("Title").innerHTML = "Playing: " + selectedObject[rand + 1];
    }
  }
  music.load();
  music.play();
};
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
Avarasd
  • 3
  • 4
  • This is an XY problem. What you want is to shuffle the selectedObject array, and then just play sequentially. In this way you guarantee that the objects are randomised, but also will not repeat itself (unless you play through the entire shuffled array). To shuffle an array you can use any of the methods in this question: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – Terry Oct 16 '22 at 21:56
  • You certainly have a lot of undefined variables there - which smells of way to many global variables here. – Mark Schultheiss Oct 16 '22 at 22:00
  • @Terry but my script should be working right? I mean I've looked through it multiple times and I don't see any reason why it's not working – Avarasd Oct 17 '22 at 14:40

0 Answers0