Skip to content
Browse files

redone events to allow binding after init method and allow for multip…

…le bindings to a single event
  • Loading branch information...
1 parent a312f76 commit 4f55794b3739f8d325f678d038b62d32e1242e11 @tommoor committed
Showing with 98 additions and 64 deletions.
  1. +27 −10 Readme.md
  2. +54 −31 Zap.js
  3. +1 −1 Zap.min.js
  4. +5 −7 examples/click.html
  5. +5 −7 examples/group.html
  6. +6 −8 examples/loop.html
View
37 Readme.md
@@ -1,6 +1,6 @@
# Zap! HTML 5 Game Audio
-Zap! is an audio manager for html 5 applications with a focus on real time uses such as games.
+Zap! is an audio manager for html 5 applications with a focus on real-time uses such as games.
It provides a common interface that works across the individual browser quirks and shortcomings such as multiple channels, looping and callbacks.
@@ -21,18 +21,35 @@ __Example__
Zap.init({
console: true,
- complete: function(){
- // callback for all sounds finished loading
- },
- error: function(ref){
- // callback when a sound fails to load
- },
- update: function(percent){
- // callback when a sound finishes loading
- }
+ container: 'sound-holder'
});
+### on(event, callback)
+
+There are currently three events that can be bound using the 'on' function; 'success', 'update' and 'error'.
+Multiple callbacks may also be bound.
+
+__Arguments__
+
+* ref - An event (success, update or error)
+* callback - A function to be called whenever the above event occurs
+
+__Example__
+
+ Zap.on('complete', function(){
+ // all sounds are loaded
+ });
+
+ Zap.on('update', function(percent){
+ // sounds are loading
+ });
+
+ Zap.on('error', function(ref){
+ // there was a problem loading a sound file
+ });
+
+
### addSound(ref, sources, channels, time)
View
85 Zap.js
@@ -9,15 +9,13 @@ var Zap = (function() {
var exports = {},
sounds = {},
groups = {},
+ events = {},
loaded = 0,
timeout = 6*1000,
self = this,
options = {
container: 'sounds',
- console: true,
- complete: function(){},
- error: function(){},
- update: function(){}
+ console: true
};
@@ -45,6 +43,31 @@ var Zap = (function() {
}
+ /**
+ * Event emitter hook
+ *
+
+ * @param {String} event
+ * @param {Function} callback to trigger on event
+ * @return {Zap} return itself to allow chaining
+ */
+ exports.on = function(event, callback){
+
+ if(! events[event]) events[event] = [];
+ events[event].push(callback);
+ return this;
+ }
+
+
+ var trigger = function(event){
+ var callbacks = events[event];
+
+ for(var c in callbacks){
+ callbacks[c].apply( this, Array.prototype.slice.call( arguments, 1 ) );
+ }
+ }
+
+
/**
* Allows sounds to be grouped under one reference, so that a random sound can be played
@@ -91,8 +114,8 @@ var Zap = (function() {
log('Zap: sound failed to load: ' + ref);
sounds[ref].failed = true;
- soundLoaded();
- options.error(ref);
+ soundLoaded();
+ trigger('error', ref);
}, time || timeout);
@@ -136,15 +159,15 @@ var Zap = (function() {
}
- /**
- * Play a sound by reference
- *
- * @param {String} ref
- * @param {Float} vol
- * @param {Integer} loops
- * @param {Function} callback
- * @return {Zap} return itself to allow chaining
- */
+ /**
+ * Play a sound by reference
+ *
+ * @param {String} ref
+ * @param {Float} vol
+ * @param {Integer} loops
+ * @param {Function} callback
+ * @return {Zap} return itself to allow chaining
+ */
exports.play = function(ref, vol, loops, c){
@@ -250,27 +273,27 @@ var Zap = (function() {
var a = document.createElement('audio');
// MP3
- this.formats.mp3 = !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
-
- // Vorbis
- this.formats.vorbis = !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''));
-
- // WAV
- this.formats.wav = !!(a.canPlayType && a.canPlayType('audio/wav; codecs="1"').replace(/no/, ''));
-
- // AAC
- this.formats.aac = !!(a.canPlayType && a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''));
-
- return this.formats;
+ this.formats.mp3 = !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
+
+ // Vorbis
+ this.formats.vorbis = !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''));
+
+ // WAV
+ this.formats.wav = !!(a.canPlayType && a.canPlayType('audio/wav; codecs="1"').replace(/no/, ''));
+
+ // AAC
+ this.formats.aac = !!(a.canPlayType && a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''));
+
+ return this.formats;
}
+
var getChannelCount = function(){
var c = 0;
for (var i in sounds) {
c += sounds[i].channels;
- }
-
+ }
return c;
}
@@ -280,9 +303,9 @@ var Zap = (function() {
var soundLoaded = function(){
loaded++;
- options.update( getPercentageLoaded() );
+ trigger('update', getPercentageLoaded() );
- if(loaded == getChannelCount()) options.complete();
+ if(loaded == getChannelCount()) trigger('complete');
}
var log = function(){
View
2 Zap.min.js
@@ -4,4 +4,4 @@
* MIT Licensed
*/
-var Zap=(function(){var k={},sounds={},groups={},loaded=0,timeout=6*1000,self=this,options={container:'sounds',console:true,complete:function(){},error:function(){},update:function(){}};k.formats={};k.init=function(a){options=$.extend(options,a);var b=document.createElement('div');b.setAttribute('id',options.container);document.body.appendChild(b);return this}k.addGroup=function(a,b){groups[a]=b;return this}k.addSound=function(a,b,d,e){var d=d||1;var f=a;sounds[a]={asset:'#'+a,loaded:false,failed:false,duration:0,channels:d,channel:0}var g=setTimeout(function(){p('Zap: sound failed to load: '+a);sounds[a].failed=true;o();options.error(a)},e||timeout);$('<div/>',{'id':a}).appendTo('#'+options.container);var c;while(d--){c='sound-'+f+'-'+d;$('<audio/>',{'id':c,'preload':'auto','autobuffer':true}).appendTo('#'+a);$('#'+c).bind('canplaythrough',function(){clearTimeout(g);sounds[a].loaded=true;sounds[a].duration=$(this).get(0).duration*1000;o()});for(var s in b){$('<source/>',{'src':b[s]}).appendTo('#'+c)}}p('Zap: sound added '+a);return this}k.play=function(a,b,d,c){if(groups[a]){var l=groups[a].length-1;var r=Math.round(Math.random()*l);a=groups[a][r]}else if(!sounds[a].loaded){p('Zap: sound with reference "'+a+'" is not loaded');return false}var e=c||function(){};var f=b||1;var g=sounds[a];var h=$('#sounds #'+a+' audio').get(g.channel);p('Zap: playing "'+a+'" on channel '+(g.channel+1));if(g.channel++>=g.channels-1){g.channel=0}h.currentTime=0;h.volume=f;h.play();if(d){var i=0;var j=setInterval(function(){if(++i<d){Zap.play(a,b);return true}clearInterval(j);e()},g.duration)}else{setTimeout(e,g.duration)}return this}k.stop=function(a){var b=$('#sounds #'+a+' audio').each(function(){$(this).get(0).pause()});return this}k.stopAllSounds=function(){$('#sounds audio').each(function(){$(this).get(0).pause()});return this}k.supported=function(){this.formats={};var a=document.createElement('audio');this.formats.mp3=!!(a.canPlayType&&a.canPlayType('audio/mpeg;').replace(/no/,''));this.formats.vorbis=!!(a.canPlayType&&a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/,''));this.formats.wav=!!(a.canPlayType&&a.canPlayType('audio/wav; codecs="1"').replace(/no/,''));this.formats.aac=!!(a.canPlayType&&a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/,''));return this.formats}var m=function(){var c=0;for(var i in sounds){c+=sounds[i].channels}return c}var n=function(){return(loaded/m())*100}var o=function(){loaded++;options.update(n());if(loaded==m())options.complete()}var p=function(){if(window.console&&options.console){window.console.log(Array.prototype.slice.call(arguments))}}return k})();
+var Zap=(function(){var exports={},sounds={},groups={},events={},loaded=0,timeout=6*1000,self=this,options={container:'sounds',console:true};exports.formats={};exports.init=function(opt){options=$.extend(options,opt);var container=document.createElement('div');container.setAttribute('id',options.container);document.body.appendChild(container);return this}exports.on=function(event,callback){if(!events[event])events[event]=[];events[event].push(callback);return this}var trigger=function(event){var callbacks=events[event];for(var c in callbacks){callbacks[c].apply(this,Array.prototype.slice.call(arguments,1))}}exports.addGroup=function(ref,sounds){groups[ref]=sounds;return this}exports.addSound=function(ref,sources,channels,time){var channels=channels||1;var element=ref;sounds[ref]={asset:'#'+ref,loaded:false,failed:false,duration:0,channels:channels,channel:0}var loadTimeout=setTimeout(function(){log('Zap: sound failed to load: '+ref);sounds[ref].failed=true;soundLoaded();trigger('error',ref)},time||timeout);$('<div/>',{'id':ref}).appendTo('#'+options.container);var c;while(channels--){c='sound-'+element+'-'+channels;$('<audio/>',{'id':c,'preload':'auto','autobuffer':true}).appendTo('#'+ref);$('#'+c).bind('canplaythrough',function(){clearTimeout(loadTimeout);sounds[ref].loaded=true;sounds[ref].duration=$(this).get(0).duration*1000;soundLoaded()});for(var s in sources){$('<source/>',{'src':sources[s]}).appendTo('#'+c)}}log('Zap: sound added '+ref);return this}exports.play=function(ref,vol,loops,c){if(groups[ref]){var l=groups[ref].length-1;var r=Math.round(Math.random()*l);ref=groups[ref][r]}else if(!sounds[ref].loaded){log('Zap: sound with reference "'+ref+'" is not loaded');return false}var callback=c||function(){};var volume=vol||1;var sound=sounds[ref];var element=$('#sounds #'+ref+' audio').get(sound.channel);log('Zap: playing "'+ref+'" on channel '+(sound.channel+1));if(sound.channel++>=sound.channels-1){sound.channel=0}element.currentTime=0;element.volume=volume;element.play();if(loops){var count=0;var loopInterval=setInterval(function(){if(++count<loops){Zap.play(ref,vol);return true}clearInterval(loopInterval);callback()},sound.duration)}else{setTimeout(callback,sound.duration)}return this}exports.stop=function(ref){var element=$('#sounds #'+ref+' audio').each(function(){$(this).get(0).pause()});return this}exports.stopAllSounds=function(){$('#sounds audio').each(function(){$(this).get(0).pause()});return this}exports.supported=function(){this.formats={};var a=document.createElement('audio');this.formats.mp3=!!(a.canPlayType&&a.canPlayType('audio/mpeg;').replace(/no/,''));this.formats.vorbis=!!(a.canPlayType&&a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/,''));this.formats.wav=!!(a.canPlayType&&a.canPlayType('audio/wav; codecs="1"').replace(/no/,''));this.formats.aac=!!(a.canPlayType&&a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/,''));return this.formats}var getChannelCount=function(){var c=0;for(var i in sounds){c+=sounds[i].channels}return c}var getPercentageLoaded=function(){return(loaded/getChannelCount())*100}var soundLoaded=function(){loaded++;trigger('update',getPercentageLoaded());if(loaded==getChannelCount())trigger('complete')}var log=function(){if(window.console&&options.console){window.console.log(Array.prototype.slice.call(arguments))}}return exports})();
View
12 examples/click.html
@@ -6,13 +6,11 @@
<script src="../Zap.js"></script>
<script>
$(function(){
- Zap.init({
- complete: function(){
- $(window).click(function(){
-
- Zap.play('laser');
- });
- }
+ Zap.init();
+ Zap.on('complete', function(){
+ $(window).click(function(){
+ Zap.play('laser');
+ });
});
Zap.addSound('laser', ['zap.mp3', 'zap.ogg'], 5);
});
View
12 examples/group.html
@@ -6,13 +6,11 @@
<script src="../Zap.js"></script>
<script>
$(function(){
- Zap.init({
- complete: function(){
-
- $(window).click(function(){
- Zap.play('zappingbeats');
- });
- }
+ Zap.init();
+ Zap.on('complete', function(){
+ $(window).click(function(){
+ Zap.play('zappingbeats');
+ });
});
Zap.addGroup('zappingbeats', ['zap', 'beat']);
View
14 examples/loop.html
@@ -6,15 +6,13 @@
<script src="../Zap.js"></script>
<script>
$(function(){
- Zap.init({
- complete: function(){
- Zap.play('beat', 1, 5, function(){
-
- alert('loop finished!');
- });
- }
+ Zap.init();
+ Zap.on('complete', function(){
+ Zap.play('beat', 1, 5, function(){
+
+ alert('loop finished!');
+ });
});
-
Zap.addSound('beat', ['beat.mp3', 'beat.ogg'], 1);
});
</script>

0 comments on commit 4f55794

Please sign in to comment.
Something went wrong with that request. Please try again.