Skip to content

Instantly share code, notes, and snippets.

@thebigbad
Created March 21, 2011 01:56
Show Gist options
  • Select an option

  • Save thebigbad/878907 to your computer and use it in GitHub Desktop.

Select an option

Save thebigbad/878907 to your computer and use it in GitHub Desktop.
looping background music in all major browsers with only moderate pain
/*
works in:
* chrome
* firefox 3.5+
* safari (with quicktime installed)
* ie 6+
I ended up only needing an ogg and mp3 version
of the file I wanted to play. Any browser that
has m4a support also worked with mp3.
I tried serving the files with node-paperboy,
but it made looping in chrome not work. Serving
files from lighttpd instead worked for me.
The ogg wasn't playing in firefox until I set
the content type to 'audio/ogg' in paperboy.
lighttpd knew the right content type without
prompting.
sources:
* http://mir.aculo.us/2011/03/16/how-to-play-a-sound-in-a-web-browser-it-aint-easy/
* http://stackoverflow.com/questions/3273552/html-5-audio-looping
* https://developer.mozilla.org/en/HTML/Element/audio
*/
var Song = function (filename) {
if (!("Audio" in window)) { return; }
var song = this,
elt = this.elt = new Audio();
var canPlay = function (c) {
return elt.canPlayType && elt.canPlayType(c).replace('no', '');
};
if (canPlay('audio/mpeg;')) {
elt.src = filename + '.mp3';
}
else if (canPlay('audio/ogg; codecs="vorbis"')) {
elt.src = filename + '.ogg';
}
else {
elt.src = filename + '.mp3';
}
if (typeof(elt.loop) == 'boolean') {
elt.loop = true;
}
else {
elt.addEventListener('ended', function() {
if (!song.playing) { return; }
elt.currentTime = 0;
elt.play();
}, false);
}
document.body.appendChild(elt);
};
Song.prototype.start = function () {
if ("Audio" in window) {
this.playing = true;
this.elt.play();
}
else {
var elt = this.elt = document.createElement('bgsound');
elt.src = this.filename + '.mp3';
elt.loop = 9;
elt.autostart = 'autostart';
document.body.appendChild(elt);
}
};
Song.prototype.stop = function () {
if ("Audio" in window) {
this.playing = false;
this.elt.pause();
}
else {
this.elt.parentNode.removeChild(this.elt);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment