Skip to content

Instantly share code, notes, and snippets.

@jasonmcleod
Created November 19, 2012 18:16
Show Gist options
  • Select an option

  • Save jasonmcleod/4112441 to your computer and use it in GitHub Desktop.

Select an option

Save jasonmcleod/4112441 to your computer and use it in GitHub Desktop.
I needed to cache a bullet sound effect, and play it several times "on top of each other". To avoid a GET request on each shot, I cache 5 copies of it and cycle through them on each play()
sounds = {
'singleshot': '/assets/sounds/singleshot.mp3'
}
for(var s in sounds) {
var path = sounds[s];
sounds[s] = {
path:path,
clones:[],
channel:0,
play:function(volume) {
this.channel = this.channel >= this.clones.length-1 ? 0 : this.channel+1
this.clones[this.channel].volume = volume || 1;
this.clones[this.channel].play()
}
};
for(var c=0;c<5;c++) { // allow up to 5 shots to be playing at once.
sounds[s].clones.push(new Audio(path))
}
}
sounds.singleshot.play(.5) // plays singleshot at half volume
sounds.singleshot.play() // plays singleshot at full volume, "on top" of the previously playing shot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment