Open demo in codepen
To play the files in the playlist infinitely with the help of the cool underscore module, you can do the following
If you are a nodejs developer you can install the module using the following command
npm i underscore
To use it in nodejs you can do the following
const _ = require("underscore")
To use it on the frontend you can put the following script just before the closing tag of the html body tag
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.2/underscore-min.js"></script>
Now lets get started with the logic
Here is my html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>SHUFFLED PLAYLIST</title>
</head>
<body>
<button id="playsong">play playlist</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.2/underscore-min.js"></script>
</body>
</html>
Here is my javascript file
let played_files = [];
let playsong = document.querySelector("#playsong");
let audio = new Audio();
let audio_files = [
"songs/song_num1.mp3",
"songs/song_num2.mp3",
"songs/song_num3.m4a",
"songs/song_num4.mp3",
];
function random_file() {
let file = _.sample(audio_files);
let allSongsPlayed = _.size(played_files) === _.size(audio_files);
if (_.contains(played_files, file) || allSongsPlayed) {
if (allSongsPlayed) {
played_files = [];
}
return random_file();
} else {
played_files.push(file);
return file;
}
}
function playSong() {
let file = random_file();
audio.src = file;
audio.play();
}
playsong.addEventListener("click", () => {
playSong();
});
audio.addEventListener("ended", playSong);