I'm creating a system where JavaScript is listening, on a websocket, for a single click or a double click from an IoT button. When the JavaScript receives the single click, it's supposed to start playing the first song in an array of shuffled audio elements. Then, once the first audio element has finished playing, it's supposed to play the next song in the array. This will go on until it is interrupted by a double click, which denotes a pause. When it gets to the end of the final song, it's to reshuffle and start from the beginning. However, I'm having trouble getting the "on end of song" function to work. Right now, it plays the first song and then stops. If I send another single click it just plays the first one from the beginning.
Javascript:
<!DOCTYPE html>
<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script>
function shuffle (input) {
for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
function startShuffle(songs){
current = 0;
for (var i = 0; i < songs.length - 1; i++) {
songs[i].onended = function () {
songs[i+1].play();
current = i + 1;
}
}
songs[songs.length - 1].onended = function () {
songs = shuffle(songs);
startShuffle(songs);
}
}
Pusher.logToConsole = true;
var current = 0;
var songs = [];
for (i = 0; i <= 100; i++) {
songs[i] = new Audio('/Users/eliavhamburger/Desktop/Ser Dree/Music/' + i + '.mp3');
}
songs = shuffle(songs);
startShuffle(songs);
var pusher = new Pusher('APIKeyHidden', {
cluster: 'us2',
encrypted: true
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
document.getElementById("demo").innerHTML = JSON.stringify(data);
if (JSON.stringify(data) == '"SINGLE"') {
songs[current].play();
}
if (JSON.stringify(data) == '"DOUBLE"') {
songs[current].pause();
}
});
</script>
</head>
<body>
<h1>Pusher Test</h1>
<p>
Try publishing an event to channel <code>my-channel</code>
with event name <code>my-event</code>.
</p>
<p ID="demo"></p>
<p ID="nums"></p>
</body>