JS Audio – update to scriptaculous sound
I’ve made a fork of scriptaculous at github and put in an important edit to sounds.js. The pull request is in but if you don’t want to wait, you can grab the updated sound.js below .
Problem
While working on a website for design firm, they noticed the problem. When navigating to another page then back, lots of sounds would fire off. Weird!
In my original JS Audio Engine I was killing the element that played the sound after a set amount of time. That cleaned up the page. However when it was folded into scriptaculous so long ago, that code was removed/changed. So it made perfect sense that when you leave the page and come back, the browser sees all those elements and plays them. I’ve never noticed it because I’ve only used sounds in one-load-websites (ajax). There was never any web page navigation involved.
Solution
Not to undo any work done when incorporated into scripty, I came up with a self cleaning solution. When the js file is loaded it creates a random number ID:
randID = 'scriptaculous-soundboard-'+Math.floor(Math.random()*1000000000);
I know there is a way to create a UUID with prototype, but I don’t know it. Anyway… upon the first sound being played a hidden div with an ID of that random number is created:
// Is the soundboard created yet?
if (!$(randID)) {
$$('body')[0].insert(
new Element('div',{
id: randID,
style: 'visibility:hidden;'
})
);
// All sounds will play from this soundboard
}
All sounds are now created within that div, instead of at the end of the BODY. When the page is left (onbeforeunload) that div is removed.
// Remove the soundboard when leaving
window.onbeforeunload = function() {
if ($(randID)) {
document.body.removeChild($(randID));
}
}
So when you navigate back, no sounds play.
Download sound.js.zip
Follow github project

Recent Comments