Created
June 20, 2013 03:59
-
-
Save bennage/5820216 to your computer and use it in GitHub Desktop.
simple implementation of pooling audio elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define(function() { | |
var pools = {}; | |
var tags = {}; | |
var manifest = { | |
'laser': ['sfx/laser.wav', 2], | |
'explosion': ['sfx/explosion.wav', 8] | |
}; | |
function createTag(src, whenReady) { | |
var tag = new Audio; | |
tag.src = src; | |
// tag.autoplay = false; | |
// tag.preload = 'none'; | |
tag.load(); | |
tag.addEventListener('canplaythrough', whenReady, true); | |
return tag; | |
} | |
function TagPool(src, channels) { | |
this.pool = []; | |
this.channels = channels; | |
this.nextIndex = 0; | |
var waitingForReady = channels; | |
for (var i = 0; i < channels; i++) { | |
this.pool[i] = createTag(src, function() { | |
waitingForReady--; | |
if (waitingForReady === 0) { | |
console.log('the pool for ' + src + ' has loaded'); | |
} | |
}); | |
} | |
} | |
TagPool.prototype.next = function() { | |
if (this.nextIndex >= this.channels) this.nextIndex = 0; | |
var tag = this.pool[this.nextIndex]; | |
// is the tag currently playing? if so, reset it | |
if (tag.currentTime != 0) { | |
// I can't find any other way to reset | |
// the sound | |
tag.load(); | |
} | |
this.nextIndex++; | |
return tag; | |
}; | |
function initialize() { | |
Object.keys(manifest).forEach(function(key) { | |
var options = manifest[key]; | |
var src = options[0]; | |
var channels = options[1] || 1; | |
pools[key] = new TagPool(src, channels); | |
}); | |
} | |
function play(key) { | |
var pool = pools[key]; | |
if (!pool) throw new Error('sfx: tag pool for ' + key + ' does not exist!'); | |
var tag = pool.next(); | |
tag.play(); | |
} | |
return { | |
initialize: initialize, | |
play: play | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment