Skip to content

Instantly share code, notes, and snippets.

@erm3nda
Last active January 21, 2019 17:11
Show Gist options
  • Save erm3nda/f105cc80a478c641ca527f13866c5f4d to your computer and use it in GitHub Desktop.
Save erm3nda/f105cc80a478c641ca527f13866c5f4d to your computer and use it in GitHub Desktop.
Javascript html5 audioplayer swapper and remember me function
/*
This code it's a mix of some good javascript fixes, a cookie manager, and audio tag features.
It ads those functions:
- Auto stop other players when starting a new one (avoid multiple sounds at time)
- Remember status of player via cookie, to autostart radio if the user wants.
Related links:
http://stackoverflow.com/questions/19790506/multiple-audio-html-auto-stop-other-when-current-is-playing-with-javascript/29045474#29045474
http://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript#24103596
*/
// cookie's stuff
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
// default audio autoload
players = document.getElementsByTagName("audio")
//~ players[0].play() // uncomment that to enable autoplay
if (readCookie("player") == "1") {
players[0].play()
}
// pause other players at play (if any) in example, podcasts previewing while listening radio or other
window.addEventListener("play", function(evt)
{
// first, create a cookie because a player was pressed
createCookie("player", "1")
// pause the current active player
if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target) // avoid pause element if it's same than previous
{
window.$_currentlyPlaying.pause();
}
window.$_currentlyPlaying = evt.target;
}, true);
// set cookie to 0 when paused
window.addEventListener("pause", function(evt)
{
createCookie("player", "0")
}, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment