Random, shuffle JavaScript playlist
I know this has been asked before, but I am new to JavaScript and after having read other answers I can't understand specifically why my method isn't working. The first track that plays is random, but then when the song ends, the same track repeats over and over again instead of choosing a different random track. If audio.play chooses a random track the first time, why doesn't it choose a random track again when the song ends, but instead loops the same track? Help appreciated:
var audio_files = [
"TRACKS/1.mp3",
"TRACKS/2.mp3",
"TRACKS/3.mp3"
]
var random_file = audio_files[Math.floor(Math.random() * audio_files.length)];
var audio = new Audio(random_file);
audio.play();
audio.addEventListener('ended', function(){
audio.play();
}
It would be easier to shuffle the array and simply iterate on it to get each file. With this solution, you will not get the same file twice because of the random solution.
Once you get to the end, do the same thing, shuffle the array and iterate again. Like this, the list will change giving the impression to selecting a different file in a random manner (but truly simply iterating).
Here is a pseudo code to it
function readFiles(){
array = shuffle(array);
for(var i = 0; i < array.length; ++i){
play(array[i]);
}
readFiles(); //to read undefinitly
}
Here and here, you will find a great threads to shuffle the array. I will not do it again, just follow the answer there.
In your case, you don't want a loop but you will use a counter the get the next file and shuffle the array again once you get to the end
function getNextFile(){
if(currentFile >= array.length){ //reach the end
shuffle(array);
currentFile = 0;
}
return array[currentFile+];
}
Your code need to be like this:
var audio_files = [
"TRACKS/1.mp3",
"TRACKS/2.mp3",
"TRACKS/3.mp3"
]
function random_file(){
return audio_files[Math.floor(Math.random() * audio_files.length)];
}
var audio = new Audio( random_file() );
audio.play();
audio.addEventListener('ended', function(){
audio.play( random_file() );
}
Your listner may be like this if player have another way to specify file for existing payer
audio.addEventListener('ended', function(){
audio.src = random_file();
audio.play();
}
or if your player have no such api method the only way is
function listner() {
audio = new Audio( random_file() );
audio.play();
audio.addEventListener('ended', listner)
}
audio.addEventListener('ended', listner)