What I find cool about these random playlist cases is to remove the elements already touched from the array, so do not risk repeating. And when you empty the array, it pops back with the original array.
I've made an adaptation of code from Caio Tarifa demonstrating the idea: JSFiddle .
To clone array is used:
tracks_clone = tracks.slice(0);
For each song played, delete the element:
tracks_clone.splice(randnum, 1);
And before starting to play, check if the clone is already empty and popular again if it is positive:
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);