What I find legal in these cases of Random playlist is to remove the already played elements from the array, so it does not risk repeating. And when you empty the array, you populate it back with the original array.
I made an adaptation of code of Caio Tarifa demonstrating the idea: Jsfiddle.
To clone the array is used:
tracks_clone = tracks.slice(0);
With each song played, delete the element:
tracks_clone.splice(randnum, 1);
And before you start playing, check to see if the clone is already empty and popular again in a positive case:
if( tracks_clone.length === 0 ) {
tracks_clone = tracks.slice(0);
}
HTML
<div id="now"></div>
<audio preload="none" id="player" controls="controls"></audio>
<button id="next">next</button>
<p id="playlist"></p>
JS
var _now = document.getElementById('now'),
_player = document.getElementById('player'),
_next = document.getElementById('next'),
_playlist = document.getElementById('playlist'),
tracks_clone,
mp3uri = 'http://www.stephaniequinn.com/Music/',
tracks = [
'Commercial%20DEMO%20-%2005.mp3',
'Commercial%20DEMO%20-%2006.mp3',
'Commercial%20DEMO%20-%2006.mp3',
];
function playNext() {
if( tracks_clone.length === 0 ) {
tracks_clone = tracks.slice(0);
}
var randnum = Math.floor(Math.random() * tracks_clone.length);
var track = tracks_clone[randnum];
_now.innerHTML = '<b>Random selected</b>: #' + randnum + '<br><b>Playing</b>: ' + decodeURIComponent(track).replace('.mp3','');
tracks_clone.splice(randnum, 1);
_playlist.innerHTML = ' - ' + decodeURIComponent(tracks_clone.join('<br> - '));
_player.src = mp3uri + track;
return _player.play();
}
function initPlayer() {
tracks_clone = tracks.slice(0);
_player.addEventListener('ended', playNext);
_next.addEventListener('click', playNext, false);
playNext();
}
window.addEventListener('load', initPlayer);
This underline before the player (
_player
) it’s a convention?– ptkato
No @Patrick, particularly like to differentiate variables from DOM variables when using Vanilla JS. :)
– Caio Tarifa