Skip to content

Instantly share code, notes, and snippets.

Created November 4, 2013 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/7305519 to your computer and use it in GitHub Desktop.
Save anonymous/7305519 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Playlist Example</title>
</head>
<body>
<ul id="tracklist">
<li class="playlist">
<a class="playlist-item" href="Miaow-01-Tempered-song">Miaow - Tempered Song</a>
</li>
<li class="playlist">
<a class="playlist-item" href="Miaow-02-Hidden">Miaow - Hidden</a>
</li>
<li class="playlist">
<a class="playlist-item" href="Miaow-03-Lentement">Miaow - Lentement</a>
</li>
</ul>
<a id="shuffle" href="#">shuffle</a>
</body>
</html>
window.onload=function(){
var myAudio = document.createElement('audio');
var playlistItems = document.getElementsByClassName('playlist-item');
var playlist = document.getElementsByClassName('playlist');
var currentTrack = "";
for(i = 0; i < playlistItems.length; i++) {
playlistItems[i].onclick = playTrackHandler;
}
function playTrackHandler() {
var src = this.getAttribute('href');
currentTrack = src;
playTrack(src);
return(false);
}
function playTrack(src) {
if (myAudio.canPlayType('audio/ogg; codecs="vorbis"')) {
src = "http://jPlayer.org/audio/ogg/" + src + ".ogg";
} else {
src = "http://jPlayer.org/audio/mp3/" + src + ".mp3";
}
myAudio.setAttribute('src',src);
myAudio.play();
}
// the ended event fires when the media has finished playing
myAudio.addEventListener('ended', function() {
for(i = 0; i < playlistItems.length; i++) {
if (playlistItems[i].getAttribute('href') == currentTrack) {
if (i < (playlistItems.length - 1)) {
playTrack(playlistItems[i+1].getAttribute('href'));
} else {
// start from the beginning (loop)
playTrack(playlistItems[0].getAttribute('href'));
}
}
}
}, false);
// assuming an element with id shuffle
var shuffleButton = document.getElementById('shuffle');
shuffleButton.onclick = shufflePlaylist;
function shuffle(els) {
var array = Array.prototype.slice.call(els, 0);
return array.sort(function(){
return 0.5 - Math.random();
});
}
// apply the shuffle to the playlist items on the DOM
function shufflePlaylist() {
var tracklist = document.getElementById('tracklist');
tracklist.innerHtml = "";
playlist = shuffle(playlist);
for (var i = 0; i < playlist.length; i++) {
tracklist.appendChild(playlist[i]);
}
playlistItems = document.getElementsByClassName('playlist-item');
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment