From 13c5dc317abe0fb4458e703f2ab9397a7c24c859 Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Mon, 16 Nov 2015 16:58:18 +0200 Subject: Rengöring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + howler.js | 1353 + howler.js-2.0.0-beta4/CHANGELOG.md | 254 + howler.js-2.0.0-beta4/LICENSE.md | 20 + howler.js-2.0.0-beta4/README.md | 315 + howler.js-2.0.0-beta4/bower.json | 6 + howler.js-2.0.0-beta4/howler.core.min.js | 2 + howler.js-2.0.0-beta4/howler.effects.min.js | 2 + howler.js-2.0.0-beta4/howler.min.js | 4 + howler.js-2.0.0-beta4/package.json | 31 + howler.js-2.0.0-beta4/src/howler.core.js | 1808 ++ .../src/plugins/howler.effects.js | 603 + howler.js-2.0.0-beta4/tests/sound1.mp3 | Bin 0 -> 1016939 bytes howler.js-2.0.0-beta4/tests/sound1.ogg | Bin 0 -> 1038603 bytes howler.js-2.0.0-beta4/tests/sound2.mp3 | Bin 0 -> 254895 bytes howler.js-2.0.0-beta4/tests/sound2.ogg | Bin 0 -> 169096 bytes howler.js-2.0.0-beta4/tests/tests.html | 66 + howler.js-2.0.0-beta4/tests/tests.js | 452 + index.html | 33 + pixi.js | 27488 +++++++++++++++++++ pixi.js.map | 1 + res/bg.mp3 | Bin 0 -> 1667051 bytes res/bg.png | Bin 0 -> 9692 bytes res/default.png | Bin 0 -> 1317 bytes res/explosion.wav | Bin 0 -> 138880 bytes res/int.png | Bin 0 -> 6446 bytes res/jump.wav | Bin 0 -> 14016 bytes res/logo1.png | Bin 0 -> 5785 bytes res/logo2.png | Bin 0 -> 5254 bytes res/playbutton.png | Bin 0 -> 5667 bytes res/player.png | Bin 0 -> 3542 bytes res/start.wav | Bin 0 -> 107396 bytes src/button.js | 18 + src/engine.js | 217 + src/gameobject.js | 20 + src/keyboard.js | 38 + src/objecttypes.js | 107 + src/platformer.js | 9 + src/player.js | 67 + src/settings.js | 15 + src/sound.js | 20 + 41 files changed, 32950 insertions(+) create mode 100644 README.md create mode 100644 howler.js create mode 100644 howler.js-2.0.0-beta4/CHANGELOG.md create mode 100644 howler.js-2.0.0-beta4/LICENSE.md create mode 100644 howler.js-2.0.0-beta4/README.md create mode 100644 howler.js-2.0.0-beta4/bower.json create mode 100644 howler.js-2.0.0-beta4/howler.core.min.js create mode 100644 howler.js-2.0.0-beta4/howler.effects.min.js create mode 100644 howler.js-2.0.0-beta4/howler.min.js create mode 100644 howler.js-2.0.0-beta4/package.json create mode 100644 howler.js-2.0.0-beta4/src/howler.core.js create mode 100644 howler.js-2.0.0-beta4/src/plugins/howler.effects.js create mode 100644 howler.js-2.0.0-beta4/tests/sound1.mp3 create mode 100644 howler.js-2.0.0-beta4/tests/sound1.ogg create mode 100644 howler.js-2.0.0-beta4/tests/sound2.mp3 create mode 100644 howler.js-2.0.0-beta4/tests/sound2.ogg create mode 100644 howler.js-2.0.0-beta4/tests/tests.html create mode 100644 howler.js-2.0.0-beta4/tests/tests.js create mode 100644 index.html create mode 100644 pixi.js create mode 100644 pixi.js.map create mode 100644 res/bg.mp3 create mode 100644 res/bg.png create mode 100644 res/default.png create mode 100644 res/explosion.wav create mode 100644 res/int.png create mode 100644 res/jump.wav create mode 100644 res/logo1.png create mode 100644 res/logo2.png create mode 100644 res/playbutton.png create mode 100644 res/player.png create mode 100644 res/start.wav create mode 100644 src/button.js create mode 100644 src/engine.js create mode 100644 src/gameobject.js create mode 100644 src/keyboard.js create mode 100644 src/objecttypes.js create mode 100644 src/platformer.js create mode 100644 src/player.js create mode 100644 src/settings.js create mode 100644 src/sound.js diff --git a/README.md b/README.md new file mode 100644 index 0000000..badb393 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# kujalan viivaintegraalipeli diff --git a/howler.js b/howler.js new file mode 100644 index 0000000..515235a --- /dev/null +++ b/howler.js @@ -0,0 +1,1353 @@ +/*! + * howler.js v1.1.28 + * howlerjs.com + * + * (c) 2013-2015, James Simpson of GoldFire Studios + * goldfirestudios.com + * + * MIT License + */ + +(function() { + // setup + var cache = {}; + + // setup the audio context + var ctx = null, + usingWebAudio = true, + noAudio = false; + try { + if (typeof AudioContext !== 'undefined') { + ctx = new AudioContext(); + } else if (typeof webkitAudioContext !== 'undefined') { + ctx = new webkitAudioContext(); + } else { + usingWebAudio = false; + } + } catch(e) { + usingWebAudio = false; + } + + if (!usingWebAudio) { + if (typeof Audio !== 'undefined') { + try { + new Audio(); + } catch(e) { + noAudio = true; + } + } else { + noAudio = true; + } + } + + // create a master gain node + if (usingWebAudio) { + var masterGain = (typeof ctx.createGain === 'undefined') ? ctx.createGainNode() : ctx.createGain(); + masterGain.gain.value = 1; + masterGain.connect(ctx.destination); + } + + // create global controller + var HowlerGlobal = function(codecs) { + this._volume = 1; + this._muted = false; + this.usingWebAudio = usingWebAudio; + this.ctx = ctx; + this.noAudio = noAudio; + this._howls = []; + this._codecs = codecs; + this.iOSAutoEnable = true; + }; + HowlerGlobal.prototype = { + /** + * Get/set the global volume for all sounds. + * @param {Float} vol Volume from 0.0 to 1.0. + * @return {Howler/Float} Returns self or current volume. + */ + volume: function(vol) { + var self = this; + + // make sure volume is a number + vol = parseFloat(vol); + + if (vol >= 0 && vol <= 1) { + self._volume = vol; + + if (usingWebAudio) { + masterGain.gain.value = vol; + } + + // loop through cache and change volume of all nodes that are using HTML5 Audio + for (var key in self._howls) { + if (self._howls.hasOwnProperty(key) && self._howls[key]._webAudio === false) { + // loop through the audio nodes + for (var i=0; i 0) ? node._pos : self._sprite[sprite][0] / 1000; + + // determine how long to play for + var duration = 0; + if (self._webAudio) { + duration = self._sprite[sprite][1] / 1000 - node._pos; + if (node._pos > 0) { + pos = self._sprite[sprite][0] / 1000 + pos; + } + } else { + duration = self._sprite[sprite][1] / 1000 - (pos - self._sprite[sprite][0] / 1000); + } + + // determine if this sound should be looped + var loop = !!(self._loop || self._sprite[sprite][2]); + + // set timer to fire the 'onend' event + var soundId = (typeof callback === 'string') ? callback : Math.round(Date.now() * Math.random()) + '', + timerId; + (function() { + var data = { + id: soundId, + sprite: sprite, + loop: loop + }; + timerId = setTimeout(function() { + // if looping, restart the track + if (!self._webAudio && loop) { + self.stop(data.id).play(sprite, data.id); + } + + // set web audio node to paused at end + if (self._webAudio && !loop) { + self._nodeById(data.id).paused = true; + self._nodeById(data.id)._pos = 0; + + // clear the end timer + self._clearEndTimer(data.id); + } + + // end the track if it is HTML audio and a sprite + if (!self._webAudio && !loop) { + self.stop(data.id); + } + + // fire ended event + self.on('end', soundId); + }, duration * 1000); + + // store the reference to the timer + self._onendTimer.push({timer: timerId, id: data.id}); + })(); + + if (self._webAudio) { + var loopStart = self._sprite[sprite][0] / 1000, + loopEnd = self._sprite[sprite][1] / 1000; + + // set the play id to this node and load into context + node.id = soundId; + node.paused = false; + refreshBuffer(self, [loop, loopStart, loopEnd], soundId); + self._playStart = ctx.currentTime; + node.gain.value = self._volume; + + if (typeof node.bufferSource.start === 'undefined') { + loop ? node.bufferSource.noteGrainOn(0, pos, 86400) : node.bufferSource.noteGrainOn(0, pos, duration); + } else { + loop ? node.bufferSource.start(0, pos, 86400) : node.bufferSource.start(0, pos, duration); + } + } else { + if (node.readyState === 4 || !node.readyState && navigator.isCocoonJS) { + node.readyState = 4; + node.id = soundId; + node.currentTime = pos; + node.muted = Howler._muted || node.muted; + node.volume = self._volume * Howler.volume(); + setTimeout(function() { node.play(); }, 0); + } else { + self._clearEndTimer(soundId); + + (function(){ + var sound = self, + playSprite = sprite, + fn = callback, + newNode = node; + var listener = function() { + sound.play(playSprite, fn); + + // clear the event listener + newNode.removeEventListener('canplaythrough', listener, false); + }; + newNode.addEventListener('canplaythrough', listener, false); + })(); + + return self; + } + } + + // fire the play event and send the soundId back in the callback + self.on('play'); + if (typeof callback === 'function') callback(soundId); + + return self; + }); + + return self; + }, + + /** + * Pause playback and save the current position. + * @param {String} id (optional) The play instance ID. + * @return {Howl} + */ + pause: function(id) { + var self = this; + + // if the sound hasn't been loaded, add it to the event queue + if (!self._loaded) { + self.on('play', function() { + self.pause(id); + }); + + return self; + } + + // clear 'onend' timer + self._clearEndTimer(id); + + var activeNode = (id) ? self._nodeById(id) : self._activeNode(); + if (activeNode) { + activeNode._pos = self.pos(null, id); + + if (self._webAudio) { + // make sure the sound has been created + if (!activeNode.bufferSource || activeNode.paused) { + return self; + } + + activeNode.paused = true; + if (typeof activeNode.bufferSource.stop === 'undefined') { + activeNode.bufferSource.noteOff(0); + } else { + activeNode.bufferSource.stop(0); + } + } else { + activeNode.pause(); + } + } + + self.on('pause'); + + return self; + }, + + /** + * Stop playback and reset to start. + * @param {String} id (optional) The play instance ID. + * @return {Howl} + */ + stop: function(id) { + var self = this; + + // if the sound hasn't been loaded, add it to the event queue + if (!self._loaded) { + self.on('play', function() { + self.stop(id); + }); + + return self; + } + + // clear 'onend' timer + self._clearEndTimer(id); + + var activeNode = (id) ? self._nodeById(id) : self._activeNode(); + if (activeNode) { + activeNode._pos = 0; + + if (self._webAudio) { + // make sure the sound has been created + if (!activeNode.bufferSource || activeNode.paused) { + return self; + } + + activeNode.paused = true; + + if (typeof activeNode.bufferSource.stop === 'undefined') { + activeNode.bufferSource.noteOff(0); + } else { + activeNode.bufferSource.stop(0); + } + } else if (!isNaN(activeNode.duration)) { + activeNode.pause(); + activeNode.currentTime = 0; + } + } + + return self; + }, + + /** + * Mute this sound. + * @param {String} id (optional) The play instance ID. + * @return {Howl} + */ + mute: function(id) { + var self = this; + + // if the sound hasn't been loaded, add it to the event queue + if (!self._loaded) { + self.on('play', function() { + self.mute(id); + }); + + return self; + } + + var activeNode = (id) ? self._nodeById(id) : self._activeNode(); + if (activeNode) { + if (self._webAudio) { + activeNode.gain.value = 0; + } else { + activeNode.muted = true; + } + } + + return self; + }, + + /** + * Unmute this sound. + * @param {String} id (optional) The play instance ID. + * @return {Howl} + */ + unmute: function(id) { + var self = this; + + // if the sound hasn't been loaded, add it to the event queue + if (!self._loaded) { + self.on('play', function() { + self.unmute(id); + }); + + return self; + } + + var activeNode = (id) ? self._nodeById(id) : self._activeNode(); + if (activeNode) { + if (self._webAudio) { + activeNode.gain.value = self._volume; + } else { + activeNode.muted = false; + } + } + + return self; + }, + + /** + * Get/set volume of this sound. + * @param {Float} vol Volume from 0.0 to 1.0. + * @param {String} id (optional) The play instance ID. + * @return {Howl/Float} Returns self or current volume. + */ + volume: function(vol, id) { + var self = this; + + // make sure volume is a number + vol = parseFloat(vol); + + if (vol >= 0 && vol <= 1) { + self._volume = vol; + + // if the sound hasn't been loaded, add it to the event queue + if (!self._loaded) { + self.on('play', function() { + self.volume(vol, id); + }); + + return self; + } + + var activeNode = (id) ? self._nodeById(id) : self._activeNode(); + if (activeNode) { + if (self._webAudio) { + activeNode.gain.value = vol; + } else { + activeNode.volume = vol * Howler.volume(); + } + } + + return self; + } else { + return self._volume; + } + }, + + /** + * Get/set whether to loop the sound. + * @param {Boolean} loop To loop or not to loop, that is the question. + * @return {Howl/Boolean} Returns self or current looping value. + */ + loop: function(loop) { + var self = this; + + if (typeof loop === 'boolean') { + self._loop = loop; + + return self; + } else { + return self._loop; + } + }, + + /** + * Get/set sound sprite definition. + * @param {Object} sprite Example: {spriteName: [offset, duration, loop]} + * @param {Integer} offset Where to begin playback in milliseconds + * @param {Integer} duration How long to play in milliseconds + * @param {Boolean} loop (optional) Set true to loop this sprite + * @return {Howl} Returns current sprite sheet or self. + */ + sprite: function(sprite) { + var self = this; + + if (typeof sprite === 'object') { + self._sprite = sprite; + + return self; + } else { + return self._sprite; + } + }, + + /** + * Get/set the position of playback. + * @param {Float} pos The position to move current playback to. + * @param {String} id (optional) The play instance ID. + * @return {Howl/Float} Returns self or current playback position. + */ + pos: function(pos, id) { + var self = this; + + // if the sound hasn't been loaded, add it to the event queue + if (!self._loaded) { + self.on('load', function() { + self.pos(pos); + }); + + return typeof pos === 'number' ? self : self._pos || 0; + } + + // make sure we are dealing with a number for pos + pos = parseFloat(pos); + + var activeNode = (id) ? self._nodeById(id) : self._activeNode(); + if (activeNode) { + if (pos >= 0) { + self.pause(id); + activeNode._pos = pos; + self.play(activeNode._sprite, id); + + return self; + } else { + return self._webAudio ? activeNode._pos + (ctx.currentTime - self._playStart) : activeNode.currentTime; + } + } else if (pos >= 0) { + return self; + } else { + // find the first inactive node to return the pos for + for (var i=0; i= 0 || x < 0) { + if (self._webAudio) { + var activeNode = (id) ? self._nodeById(id) : self._activeNode(); + if (activeNode) { + self._pos3d = [x, y, z]; + activeNode.panner.setPosition(x, y, z); + activeNode.panner.panningModel = self._model || 'HRTF'; + } + } + } else { + return self._pos3d; + } + + return self; + }, + + /** + * Fade a currently playing sound between two volumes. + * @param {Number} from The volume to fade from (0.0 to 1.0). + * @param {Number} to The volume to fade to (0.0 to 1.0). + * @param {Number} len Time in milliseconds to fade. + * @param {Function} callback (optional) Fired when the fade is complete. + * @param {String} id (optional) The play instance ID. + * @return {Howl} + */ + fade: function(from, to, len, callback, id) { + var self = this, + diff = Math.abs(from - to), + dir = from > to ? 'down' : 'up', + steps = diff / 0.01, + stepTime = len / steps; + + // if the sound hasn't been loaded, add it to the event queue + if (!self._loaded) { + self.on('load', function() { + self.fade(from, to, len, callback, id); + }); + + return self; + } + + // set the volume to the start position + self.volume(from, id); + + for (var i=1; i<=steps; i++) { + (function() { + var change = self._volume + (dir === 'up' ? 0.01 : -0.01) * i, + vol = Math.round(1000 * change) / 1000, + toVol = to; + + setTimeout(function() { + self.volume(vol, id); + + if (vol === toVol) { + if (callback) callback(); + } + }, stepTime * i); + })(); + } + }, + + /** + * [DEPRECATED] Fade in the current sound. + * @param {Float} to Volume to fade to (0.0 to 1.0). + * @param {Number} len Time in milliseconds to fade. + * @param {Function} callback + * @return {Howl} + */ + fadeIn: function(to, len, callback) { + return this.volume(0).play().fade(0, to, len, callback); + }, + + /** + * [DEPRECATED] Fade out the current sound and pause when finished. + * @param {Float} to Volume to fade to (0.0 to 1.0). + * @param {Number} len Time in milliseconds to fade. + * @param {Function} callback + * @param {String} id (optional) The play instance ID. + * @return {Howl} + */ + fadeOut: function(to, len, callback, id) { + var self = this; + + return self.fade(self._volume, to, len, function() { + if (callback) callback(); + self.pause(id); + + // fire ended event + self.on('end'); + }, id); + }, + + /** + * Get an audio node by ID. + * @return {Howl} Audio node. + */ + _nodeById: function(id) { + var self = this, + node = self._audioNode[0]; + + // find the node with this ID + for (var i=0; i=0; i--) { + if (inactive <= 5) { + break; + } + + if (self._audioNode[i].paused) { + // disconnect the audio source if using Web Audio + if (self._webAudio) { + self._audioNode[i].disconnect(0); + } + + inactive--; + self._audioNode.splice(i, 1); + } + } + }, + + /** + * Clear 'onend' timeout before it ends. + * @param {String} soundId The play instance ID. + */ + _clearEndTimer: function(soundId) { + var self = this, + index = 0; + + // loop through the timers to find the one associated with this sound + for (var i=0; i= 0) { + Howler._howls.splice(index, 1); + } + + // delete this sound from the cache + delete cache[self._src]; + self = null; + } + + }; + + // only define these functions when using WebAudio + if (usingWebAudio) { + + /** + * Buffer a sound from URL (or from cache) and decode to audio source (Web Audio API). + * @param {Object} obj The Howl object for the sound to load. + * @param {String} url The path to the sound file. + */ + var loadBuffer = function(obj, url) { + // check if the buffer has already been cached + if (url in cache) { + // set the duration from the cache + obj._duration = cache[url].duration; + + // load the sound into this object + loadSound(obj); + return; + } + + if (/^data:[^;]+;base64,/.test(url)) { + // Decode base64 data-URIs because some browsers cannot load data-URIs with XMLHttpRequest. + var data = atob(url.split(',')[1]); + var dataView = new Uint8Array(data.length); + for (var i=0; i + Howl (group) -> + Sound (single) +``` + +Howler.js now also has the concept of plugins. The core represents 100% compatibility across hTML5 Audio and Web Audio, adhering to the initial goals of the library. There is also a new Effects Plugin that adds advanced features only available in the Web Audio API. + +- `ADDED`: Lots of general code cleanup, simplification and reogranziation. +- `ADDED`: Howler.js is now modularized. The core represents the initial goal for howler.js with 100% compatibility across hTML5 Audio and Web Audio. The effects plugin adds many of the advanced features provided by the Web Audio API. +- `ADDED`: The new structure allows for full control of sprite playback (this was buggy or didn't work at all before). +- `ADDED`: New `once` method to setup event listeners that will automatically remove themselves once fired. +- `ADDED`: New `playing` method that will return `true` if the specified sound is currently playing. +- `ADDED`: New `duration` method that will return the duration of the audio source. +- `ADDED`: New `preload` property to allow disabling the auto-preload functionality. +- `ADDED`: New `faded` event that fires at the completion of a fade-in or fade-out. +- `ADDED`: New `stop` event that fires when `stop` is called, but not when the sound ends (`end` event already exists for that). +- `ADDED`: New `pool` property to allow setting the inactive sound pool size (for advanced use, still defaults to 5). +- `ADDED`: Third parameter to `on`, `once` and `off` to allow listening or removing events for only a specific sound id. +- `ADDED`: The following methods now alter all sounds within a `Howl` group when no `id` is passed: `pause`, `stop`, `volume`, `fade`, `mute`, `loop`. +- `ADDED`: The `rate` property now changes the playback rate on both Web Audio and HTML5 Audio. +- `ADDED`: New `rate` method that allows changing playback rate at runtime. +- `ADDED`: New global `unload` method. +- `ADDED`: Support for .webm extension in addition to .weba. +- `ADDED`: New codec recommendations and notes have been added to the documentation. +- `ADDED`: (Effects) New `Howler` listener methods `pos`, `orientation`, `velocity` and `listenerAttr`. +- `ADDED`: (Effects) New `Howl` methods `pos`, `orientation`, `velocity` and `pannerAttr` to control spatial audio of single sounds or groups of sounds. +- `ADDED`: (Effects) `pannerAttr` allows for control of `coneInnerAngle`, `coneOUterAngle`, `coneOuterGain`, `distanceModel`, `maxDistance`, `panningModel`, `refDistance` and `rolloffFactor`. +- `UPDATED`: (Effects) When using Web Audio, a panner node is only added when spatial audio is used. +- `UPDATED`: The `play` method no longer takes a callback and immediately returns the playback sound id (this means you can no longer chain onto the `play` method, but all others work the same). +- `UPDATED`: Changed property names `buffer` to `html5` and `pos` to `seek`. +- `UPDATED`: The global, group and single sound `mute` and `unmute` methods have been combined into a single `mute` method. +- `UPDATED`: The AMD definition is now namespaced to `howler`. +- `UPDATED`: The deprecated `fadeIn` and `fadeOut` methods have been removed in favor of the single `fade` method. +- `UPDATED`: Improved the `ext` property and made it especially usefully for playing streams (for example, SoundCloud). +- `UPDATED`: The `fade` method now only uses timeouts as a fallback with HTML5 Audio. +- `UPDATED`: Moved any needed try/catch statements into own methods to prevent de-optimization in V8 and others. +- `UPDATED`: Updated and improved overall documentation. +- `UPDATED`: Fades are now automatically stopped when a new one is started, volume is changed or the sound is paused/stopped. +- `UPDATED`: Automatically checks for disabled audio in Internet Explorer. +- `FIXED`: The event system has been overhauled to be more reliable. +- `FIXED`: Methods called before a sound has loaded no longer cause events to stick in the queue. +- `FIXED`: The `end` event correctly fires at the end of each loop when using Web Audio. +- `FIXED`: Fixed several issues with playback of sprites. +- `FIXED`: Fixed several issues with playback timing after pausing sounds. +- `FIXED`: Improved support for seeking a sound while it is playing. +- `FIXED`: When playback rate is changed, the `end` event now fires at the correct time. +- `FIXED`: Fixed a potential memory leak when using the `unload` method. +- `FIXED`: Calling `pause` on a sound that hasn't yet loaded now works correctly. +- `FIXED`: Muting a sound while it is fading now works. +- `FIXED`: Playback of base64 encoded sounds in Internet Explorer 9. +- `FIXED`: MIME check for some base64 encoded MP3's. +- `FIXED`: Now tries to automatically unlock audio on mobile browsers besides Mobile Safari. + +## 1.1.25 (July 29, 2014) +- `ADDED`: The `AudioContext` is now available on the global `Howler` object (thanks Matt DesLauriers). +- `FIXED`: When falling back to HTML5 Audio due to XHR error, delete cache for source file to prevent multi-playback issues. + +## 1.1.24 (July 20, 2014) +- `FIXED`: Improved performance of loading files using data URIs (thanks Rob Wu). +- `FIXED`: Data URIs now work with Web Audio API (thanks Rob Wu). +- `FIXED`: Omitting the second parameter of the `off` method now correctly clears all events by that name (thanks Gabriel Munteanu). +- `FIXED`: Fire `end` event when unloading playing sounds. +- `FIXED`: Small error fix in iOS check. + +## 1.1.23 (July 2, 2014) +- `FIXED`: Playing multiple sprites rapdily with HTML5 Audio cause the sprite to break due to a v1.1.22 update. +- `FIXED`: Don't run the iOS test if there is no audio context, which prevents a breaking error. + +## 1.1.22 (June 28, 2014) +- `ADDED`: Howler will now automatically attempt to unlock audio on iOS (thanks Federico Brigante). +- `ADDED`: New `codecs` global Howler method to check for codec support in the current browser (thanks Jay Oster). +- `FIXED`: End timers are now correctly cleaned up when a sound naturally completes rather than being forced to stop. + +## 1.1.21 (May 28, 2014) +- `ADDED`: Support for npm and bower (thanks Morantron). +- `ADDED`: Support for audio/aac, audio/m4a and audio/mp4 mime types (thanks Federico Brigante). +- `FIXED`: Fixed calculation of duration after pausing a sprite that was sometimes causing unexpected behavior. +- `FIXED`: Clear the event listener when creating a new HTML5 Audio node. + +## 1.1.20 (April 18, 2014) +- `ADDED`: When using Web Audio API, the panningModel now defaults to 'equalpower' to give higher quality sound. It then automatically switches to 'HRTF' when using 3D sound. This can also be overridden with the new `model` property. +- `FIXED`: Fixed another bug causing issues in CocoonJS (thanks Olivier Biot). +- `FIXED`: Fixed an issue that could have caused invalid state errors and a memory leak when unloading in Internet Explorer. +- `FIXED`: The documentation has been updated to include the `rate` property. + +## 1.1.19 (April 14, 2014) +- `ADDED`: Added CocoonJS support (thanks Olivier Biot). +- `FIXED`: Fixed several issues with pausing sprite instances by overhauling how end timers are tracked and cleared internally. +- `FIXED`: Prevent error when using a server-side require where window is absent (thanks AlexMost). + +## 1.1.18 (March 23, 2014) +- `FIXED`: Muting a looping sound now correctly keeps the sound muted when using HTML5 Audio. +- `FIXED`: Wrap AudioContext creation in try/catch to gracefully handle browser bugs: [Chromium issue](https://code.google.com/p/chromium/issues/detail?id=308784) (thanks Chris Buckley). +- `FIXED`: Listen for HTML5 Audio errors and fire `loaderror` if any are encountered (thanks digitaltonic). + +## 1.1.17 (February 5, 2014) +- `FIXED`: Fix another bug in Chrome that would throw an error when pausing/stopping when a source is already stopped. +- `ADDED`: CommonJS support for things like Browserify (thanks Michal Kuklis). +- `ADDED`: Support for playback mp4 files. +- `ADDED`: Expose the `noAudio` variable to the global `Howler` object. +- `FIXED`: Fix a rounding error that was causing HTML5 Audio to cut off early on some environments. +- `FIXED`: The `onend` callback now correctly fires when changing the pos of a sound after it has started playing and when it is using HTML5 Audio. + +## 1.1.16 (January 8, 2014) +- `FIXED`: Prevent InvalidStateError when unloading a sound that has already been stopped. +- `FIXED`: Fix bug in unload method that prevented the first sound from being unloaded. + +## 1.1.15 (December 28, 2013) +- `FIXED`: Fix bug that prevented master volume from being set to 0. +- `FIXED`: Fix bug that prevented initial volume from being set to 0. +- `FIXED`: Update the README to accurately show `autoplay` as defaulting to `false`. +- `FIXED`: Call `loaderror` when decodeAudioData fails. +- `FIXED`: Fix bug in setting position on an active playing WebAudio node through 'pos(position, id)' (thanks Arjun Mehta). +- `FIXED`: Fix an issue with looping after resuming playback when in WebAudio playback (thanks anzev). + +## 1.1.14 (October 18, 2013) +- `FIXED`: Critical bug fix that was breaking support on some browsers and some codecs. + +## 1.1.13 (October 17, 2013) +- `FIXED`: Code cleanup by removing redundant `canPlay` object (thanks Fabien). +- `FIXED`: File extensions are now detected correctly if there is a query string with dots in the filename (thanks theshock). +- `FIXED`: Fire `onloaderror` if a bad filename is passed with the `urls` property. + +## 1.1.12 (September 12, 2013) +- `UPDATED`: Changed AMD definition to anonymous module and define it as global always (thanks Fabien). +- `ADDED`: Added the `rate` property to `Howl` object creation, allowing you to specify the playback rate. This only works when using Web Audio (thanks Qqwy). +- `FIXED`: Prevent some instances of IE9 from throwing "Not Implemented" error (thanks Tero Tilus). + +## 1.1.11 (July 28, 2013) +- `FIXED`: Fix bug caused by trying to disconnect audio node when using HTML5 Audio. +- `FIXED`: Correctly return the sound's position when it is paused. +- `FIXED`: Fix another bug that caused looping sounds to not always correctly resume after a pause. + +## 1.1.10 (July 26, 2013) +- `ADDED`: New `unload` method to destroy a Howl object. This will stop all associated sounds instantly and remove the sound from the cache. +- `FIXED`: When using Web Audio, loop from the correct position after pausing the sound halfway through. +- `FIXED`: Always return a number when getting a sound's position with the `pos` method, and always return the reference to the sound when setting a sound that hasn't loaded. + +## 1.1.9 (July 11, 2013) +- `FIXED`: Fixed issue where calling the `volume` method before a sound had loaded prevented the volume from being changed. + +## 1.1.8 (July 10, 2013) +- `FIXED`: `urls` method now works again, and can take a string rather than an array if only one url is being passed. +- `FIXED`: Make `node.play` async when not using webAudio (thanks Alex Dong). + +## 1.1.7 (May 30, 2013) +- `FIXED`: Hotfix for a missing parameter that somehow missed the 1.1.6 commit in global muting. + +## 1.1.6 (May 30, 2013) +- `ADDED`: A general `fade` method that allows a playing sound to be faded from one volume to another. +- `DEPRECATED`: The `fadeIn` and `fadeOut` methods should no longer be used and have been deprecated. These will be removed in a future major release. +- `FIXED`: No longer require the sprite parameter to be passed into the `play` method when just passing a callback function. +- `FIXED`: Cleaned up global muting code. (thanks arnorhs). + +## 1.1.5 (May 3, 2013) +- `ADDED`: Support for the Ogg Opus codec (thanks Andrew Carpenter). +- `ADDED`: Semver tags for easy package management (thanks Martin Reurings). +- `ADDED`: Improve style/readability of code that discovers which audio file extension to use (thanks Fabien). +- `ADDED`: The `onend` event now passes the soundId back as the 2nd parameter of the callback (thanks Ross Cairns). +- `FIXED`: A few small typos in the comments. (thanks VAS). + +## 1.1.4 (April 28, 2013) +- `FIXED`: A few small bugs that broke global mute and unmute when using HTML5 Audio. + +## 1.1.3 (April 27, 2013) +- `FIXED`: Bug that prevented global mute from working 100% of the time when using HTML5 Audio. + +## 1.1.2 (April 24, 2013) +- `FIXED`: Calling `volume` before `play` now works as expected. +- `FIXED`: Edge case issue with cache cleaning. +- `FIXED`: Load event didn't fire when new URLs were loaded after the initial load. + +## 1.1.1 (April 17, 2013) +- `ADDED`: `onloaderror` event fired when sound fails to load (thanks Thiago de Barros Laceda). +- `ADDED`: `format` property that overrides the URL extraction of the file format (thanks Kenan Shifflett). +- `FIXED`: AMD implementation now only defines one module and removes global scope (thanks Kenan Shifflett). +- `FIXED`: Broken chaining with `play` method. + +## 1.1.0 (April 11, 2013) +- `ADDED:` New `pos3d` method that allows for positional audio (Web Audio API only). +- `ADDED:` Multi-playback control system that allows for control of specific play instances when sprites are used. A callback has been added to the `play` method that returns the `soundId` for the playback instance. This can then be passed as the optional last parameter to other methods to control that specific playback instead of the whole sound object. +- `ADDED:` Pass the `Howl` object reference as the first parameter in the custom event callbacks. +- `ADDED:` New optional parameter in sprite defintions to define a sprite as looping rather than the whole track. In the sprite definition array, set the 3rd value to true for looping (`spriteName: [pos, duration, loop]`). +- `FIXED:` Now all audio acts as a sound sprite internally, which helps to fix several lingering bugs (doesn't affect the API at all). +- `FIXED:` Improved implementation of Web Audio API looping. +- `FIXED:` Improved implementation of HTML5 Audio looping. +- `FIXED:` Issue that caused the fallback to not work when testing locally. +- `FIXED:` Fire `onend` event at the end of `fadeOut`. +- `FIXED:` Prevent errors from being thrown on browsers that don't support HTML5 Audio. +- `FIXED:` Various code cleanup and optimizations. + +## 1.0.13 (March 20, 2013) +- `ADDED:` Support for AMD loading as a module (thanks @mostlygeek). + +## 1.0.12 (March 28, 2013) +- `ADDED:` Automatically switch to HTML5 Audio if there is an error due to CORS. +- `FIXED:` Check that only numbers get passed into volume methods. + +## 1.0.11 (March 8, 2013) +- `ADDED:` Exposed `usingWebAudio` value through the global `Howler` object. +- `FIXED:` Issue with non-sprite HTML5 Audio clips becoming unplayable (thanks Paul Morris). + +## 1.0.10 (March 1, 2013) +- `FIXED:` Issue that caused simultaneous playback of audio sprites to break while using HTML5 Audio. + +## 1.0.9 (March 1, 2013) +- `ADDED:` Spec-implementation detection to cover new and deprecated Web Audio API methods (thanks @canuckistani). + +## 1.0.8 (February 25, 2013) +- `ADDED:` New `onplay` event. +- `ADDED:` Support for playing audio from base64 encoded strings. +- `FIXED:` Issue with soundId not being unique when multiple sounds were played simultaneously. +- `FIXED:` Verify that an HTML5 Audio Node is ready to play before playing it. +- `FIXED:` Issue with `onend` timer not getting cleared all the time. + +## 1.0.7 (February 18, 2013) +- `FIXED:` Cancel the correct timer when multiple HTML5 Audio sounds are played at the same time. +- `FIXED:` Make sure howler.js is future-compatible with UglifyJS 2. +- `FIXED:` Duration now gets set correctly when pulled from cache. +- `FIXED:` Tiny typo in README.md (thanks @johnfn). + +## 1.0.6 (February 8, 2013) +- `FIXED:` Issue with global mute calls happening before an HTML5 Audio element is loaded. + +## 1.0.5 (February 7, 2013) +- `FIXED:` Global mute now also mutes all future sounds that are played until `unmute` is called. + +## 1.0.4 (February 6, 2013) +- `ADDED:` Support for WebM audio. +- `FIXED:` Issue with volume changes when on HTML5 Audio. +- `FIXED:` Round volume values to fix inconsistencies in fade in/out methods. + +## 1.0.3 (February 2, 2013) +- `FIXED:` Make sure `self` is always defined before returning it. + +## 1.0.2 (February 1, 2013) +- `ADDED:` New `off` method that allows for the removal of custom events. +- `FIXED:` Issue with chaining the `on` method. +- `FIXED:` Small typo in documentation. + +## 1.0.1 (January 30, 2013) +- `ADDED:` New `buffer` property that allows you to force the use of HTML5 on specific sounds to allow streaming of large audio files. +- `ADDED:` Support for multiple events per event type. +- `FIXED:` Issue with method chaining before a sound was ready to play. +- `FIXED:` Use `self` everywhere instead of `this` to maintain consistency. + +## 1.0.0 (January 28, 2013) +- First commit \ No newline at end of file diff --git a/howler.js-2.0.0-beta4/LICENSE.md b/howler.js-2.0.0-beta4/LICENSE.md new file mode 100644 index 0000000..cc37b73 --- /dev/null +++ b/howler.js-2.0.0-beta4/LICENSE.md @@ -0,0 +1,20 @@ +Copyright (c) 2013-2014 James Simpson and GoldFire Studios, Inc. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/howler.js-2.0.0-beta4/README.md b/howler.js-2.0.0-beta4/README.md new file mode 100644 index 0000000..57ab23d --- /dev/null +++ b/howler.js-2.0.0-beta4/README.md @@ -0,0 +1,315 @@ +![howler.js](http://goldfirestudios.com/proj/howlerjs/howlerjs_logo.png "howler.js") + +## Description +[**howler.js**](http://howlerjs.com) is an audio library for the modern web. It defaults to [Web Audio API](http://webaudio.github.io/web-audio-api/) and falls back to [HTML5 Audio](http://www.whatwg.org/specs/web-apps/current-work/#the-audio-element). + +More documentation, examples and demos can be found at **[howlerjs.com](http://howlerjs.com)**. + +### Features +* Defaults to Web Audio API +* Falls back to HTML5 Audio +* Supports multiple file formats to support all browsers +* Automatic caching for Web Audio API +* Implements cache pool for HTML5 Audio +* Per-sound and global mute/unmute and volume control +* Playback of multiple sounds at the same time +* Easy sound sprite definition and playback +* Fade in/out sounds +* Supports Web Audio 3D sound positioning +* Methods can be chained +* Uses no outside libraries, just pure Javascript +* Lightweight, 9kb filesize (3kb gzipped) + +### Browser Compatibility +Tested in the following browsers/versions: +* Google Chrome 7.0+ +* Internet Explorer 9.0+ +* Firefox 4.0+ +* Safari 5.1.4+ +* Mobile Safari 6.0+ (after user input) +* Opera 12.0+ + +## Documentation + +### Examples + +##### Most basic, play an MP3: +```javascript +var sound = new Howl({ + src: ['sound.mp3'] +}); + +sound.play(); +``` + +##### More playback options: +```javascript +var sound = new Howl({ + src: ['sound.ogg', 'sound.mp3', 'sound.wav'], + autoplay: true, + loop: true, + volume: 0.5, + onend: function() { + console.log('Finished!'); + } +}); +``` + +##### Define and play a sound sprite: +```javascript +var sound = new Howl({ + src: ['sounds.ogg', 'sounds.mp3'], + sprite: { + blast: [0, 1000], + laser: [2000, 3000], + winner: [4000, 7500] + } +}); + +// shoot the laser! +sound.play('laser'); +``` + + +### Core Properties +#### src `Array` `[]` *`required`* +The sources to the track(s) to be loaded for the sound (URLs or base64 data URIs). These should be in order of preference, howler.js will automatically load the first one that is compatible with the current browser. If your files have no extensions, you will need to explicitly specify the extension using the `ext` property. +#### volume `Number` `1.0` +The volume of the specific track, from `0.0` to `1.0`. +#### html5 `Boolean` `false` +Set to `true` to force HTML5 Audio. This should be used for large audio files so that you don't have to wait for the full file to be downloaded and decoded before playing. +#### loop `Boolean` `false` +Set to `true` to automatically loop the sound forever. +#### preload `Boolean` `true` +Automatically begin downloading the audio file when the `Howl` is defined. +#### autoplay `Boolean` `false` +Set to `true` to automatically start playback when sound is loaded. +#### mute `Boolean` `false` +Set to `true` to load the audio muted. +#### sprite `Object` `{}` +Define a sound sprite for the sound. The offset and duration are defined in milliseconds. A third (optional) parameter is available to set a sprite as looping. An easy way to generate compatible sound sprites is with [audiosprite](https://github.com/tonistiigi/audiosprite). +```javascript +{ + key: [offset, duration, (loop)] +} +``` +#### rate `Number` `1.0` +The rate of playback. 0.5 to 4.0, with 1.0 being normal speed. +#### pool `Number` `5` +The size of the inactive sounds pool. Once sounds are stopped or finish playing, they are marked as ended and ready for cleanup. We keep a pool of these to recycle for improved performance. Generally this doesn't need to be changed. It is important to keep in mind that when a sound is paused, it won't be removed from the pool and will still be considered active so that it can be resumed later. +#### ext `Array` `[]` +howler.js automatically detects your file format from the extension, but you may also specify a format in situations where extraction won't work (such as with a SoundCloud stream). +#### onload `Function` +Fires when the sound is loaded. +#### onloaderror `Function` +Fires when the sound is unable to load. The first parameter is the ID of the sound (if it exists) and the second is the error message/code. +#### onplay `Function` +Fires when the sound begins playing. The first parameter is the ID of the sound. +#### onend `Function` +Fires when the sound finishes playing (if it is looping, it'll fire at the end of each loop). The first parameter is the ID of the sound. +#### onpause `Function` +Fires when the sound has been paused. The first parameter is the ID of the sound. +#### onstop `Function` +Fires when the sound has been stopped. The first parameter is the ID of the sound. +#### onfaded `Function` +Fires when the current sound finishes fading in/out. The first parameter is the ID of the sound. + + +### Core Methods +#### play([sprite/id]) +Begins playback of a sound. Returns the sound id to be used with other methods. Only method that can't be chained. +* **sprite/id**: `String/Number` `optional` Takes one parameter that can either be a sprite or sound ID. If a sprite is passed, a new sound will play based on the sprite's definition. If a sound ID is passed, the previously played sound will be played (for example, after puasing it). However, if an ID of a sound that has been drained from the pool is passed, nothing will play. + +#### pause([id]) +Pauses playback of sound or group, saving the `seek` of playback. +* **id**: `Number` `optional` The sound ID. If none is passed, all sounds in group are puased. + +#### stop([id]) +Stops playback of sound, resetting `seek` to `0`. +* **id**: `Number` `optional` The sound ID. If none is passed, all sounds in group are stopped. + +#### mute([muted], [id]) +Mutes the sound, but doesn't pause the playback. +* **muted**: `Boolean` `optional` True to mute and false to unmute. +* **id**: `Number` `optional` The sound ID. If none is passed, all sounds in group are stopped. + +#### volume([volume], [id]) +Get/set volume of this sound or the group. This method optionally takes 0, 1 or 2 arguments. +* **volume**: `Number` `optional` Volume from `0.0` to `1.0`. +* **id**: `Number` `optional` The sound ID. If none is passed, all sounds in group have volume altered relative to their own volume. + +#### fade(from, to, duration, [id]) +Fade a currently playing sound between two volumes. Fires the `faded` event when complete. +* **from**: `Number` Volume to fade from (`0.0` to `1.0`). +* **to**: `Number` Volume to fade to (`0.0` to `1.0`). +* **duration**: `Number` Time in milliseconds to fade. +* **id**: `Number` `optional` The sound ID. If none is passed, all sounds in group will fade. + +#### rate([rate], [id]) +Get/set the rate of playback for a sound. This method optionally takes 0, 1 or 2 arguments. +* **rate**: `Number` `optional` The rate of playback. 0.5 to 4.0, with 1.0 being normal speed. +* **id**: `Number` `optional` The sound ID. If none is passed, playback rate of all sounds in group will change. + +#### seek([seek], [id]) +Get/set the position of playback for a sound. This method optionally takes 0, 1 or 2 arguments. +* **seek**: `Number` `optional` The position to move current playback to (in seconds). +* **id**: `Number` `optional` The sound ID. If none is passed, the first sound will seek. + +#### loop([loop], [id]) +Get/set whether to loop the sound or group. This method can optionally take 0, 1 or 2 arguments. +* **loop**: `Boolean` `optional` To loop or not to loop, that is the question. +* **id**: `Number` `optional` The sound ID. If none is passed, all sounds in group will have their `loop` property updated. + +#### playing(id) +Check if a sound is currently playing or not, returns a `Boolean`. +* **id**: `Number` The sound ID to check. + +#### duration() +Get the duration of the audio source. Will return 0 until after the `load` event fires. + +#### on(event, function, [id]) +Listen for events. Multiple events can be added by calling this multiple times. +* **event**: `String` Name of event to fire/set (`load`, `loaderror`, `play`, `end`, `pause`, `stop`, `faded`). +* **function**: `Function` Define function to fire on event. +* **id**: `Number` `optional` Only listen to events for this sound id. + +#### once(event, function, [id]) +Same as `on`, but it removes itself after the callback is fired. +* **event**: `String` Name of event to fire/set (`load`, `loaderror`, `play`, `end`, `pause`, `stop`, `faded`). +* **function**: `Function` Define function to fire on event. +* **id**: `Number` `optional` Only listen to events for this sound id. + +#### off(event, [function], [id]) +Remove event listener that you've set. +* **event**: `String` Name of event (`load`, `loaderror`, `play`, `end`, `pause`, `stop`, `faded`). +* **function**: `Function` `optional` The listener to remove. Omit this to remove all events of type. +* **id**: `Number` `optional` Only remove events for this sound id. + +#### load() +This is called by default, but if you set `preload` to false, you must call `load` before you can play any sounds. + +#### unload() +Unload and destroy a Howl object. This will immediately stop all sounds attached to this sound and remove it from the cache. + +### Global Core Methods +The following methods are used to modify all sounds globally, and are called from the `Howler` object. +#### mute(muted) +Mute or unmute all sounds. +* **muted**: `Boolean` True to mute and false to unmute. + +#### volume([volume]) +Get/set the global volume for all sounds, relative to their own volume. +* **volume**: `Number` `optional` Volume from `0.0` to `1.0`. + +#### codecs(ext) +Check supported audio codecs. Returns `true` if the codec is supported in the current browser. +* **ext**: `String` File extension. One of: "mp3", "opus", "ogg", "wav", "aac", "m4a", "mp4", "weba". + +#### unload() +Unload and destroy all currently loaded Howl objects. This will immediately stop all sounds and remove them from cache. + + +### Global Core Properties +#### usingWebAudio `Boolean` +`true` if the Web Audio API is available. +#### noAudio `Boolean` +`true` if any audio is available. +#### mobileAutoEnable `Boolean` `true` +Automatically attempts to enable audio on mobile (iOS, Android, etc) devices. +#### ctx `Boolean` *`Web Audio Only`* +Exposes the `AudioContext` with Web Audio API. + + +### Plugin: Effects Methods +#### pos(x, y, z, [id]) +Get/set the 3D spatial position of the audio source for this sound or group. The most common usage is to set the `x` position for left/right panning. Setting any value higher than `1.0` will begin to decrease the volume of the sound as it moves further away. +* **x**: `Number` The x-position of the audio from `-1000.0` to `1000.0`. +* **y**: `Number` The y-position of the audio from `-1000.0` to `1000.0`. +* **z**: `Number` The z-position of the audio from `-1000.0` to `1000.0`. +* **id**: `Number` `optional` The sound ID. If none is passed, all in group will be updated. + +#### orientation(x, y, z, [id]) +Get/set the direction the audio source is pointing in the 3D cartesian coordinate space. Depending on how direction the sound is, based on the `cone` attributes, a sound pointing away from the listener can be quiet or silent. +* **x**: `Number` The x-orientation of the source. +* **y**: `Number` The y-orientation of the source. +* **z**: `Number` The z-orientation of the source. +* **id**: `Number` `optional` The sound ID. If none is passed, all in group will be updated. + +#### velocity(x, y, z, [id]) +Get/set the velocity vector of the audio source or group. This controls both direction and speed in 3D space and is relative to the listener's velocity. The units are meters/second and are independent of position and orientation. +* **x**: `Number` The x-velocity of the source. +* **y**: `Number` The y-velocity of the source. +* **z**: `Number` The z-velocity of the source. +* **id**: `Number` `optional` The sound ID. If none is passed, all in group will be updated. + +#### pannerAttr(o, [id]) +Get/set the panner node's attributes for a sound or group of sounds. This method can optionall take 0, 1 or 2 arguments. +* **o**: `Object` All values to update. + * **coneInnerAngle** `360` There will be no volume reduction inside this angle. + * **coneOUterAngle** `360` The volume will be reduced to a constant value of `coneOuterGain` outside this angle. + * **coneOuterGain** `0` The amount of volume reduction outside of `coneOuterAngle`. + * **distanceModel** `inverse` Determines algorithm to use to reduce volume as audio moves away from listener. Can be `linear`, `inverse` or `exponential. + * **maxDistance** `10000` Volume won't reduce between source/listener beyond this distance. + * **panningModel** `HRTF` Determines which spatialization algorithm is used to position audio. Can be `HRTF` or `equalpower`. + * **refDistance** `1` A reference distance for reducing volume as the source moves away from the listener. + * **rolloffFactor** `1` How quickly the volume reduces as source moves from listener. +* **id**: `Number` `optional` The sound ID. If none is passed, all in group will be updated. + + +### Plugin: Effects Properties +#### orientation `Array` `[1, 0, 0]` +Sets the direction the audio source is pointing in the 3D cartesian coordinate space. Depending on how direction the sound is, based on the `cone` attributes, a sound pointing away from the listener can be quiet or silent. +#### pos `Array` `null` +Sets the 3D spatial position of the audio source for this sound or group. The most common usage is to set the `x` position for left/right panning. Setting any value higher than `1.0` will begin to decrease the volume of the sound as it moves further away. +#### velocity `Array` `[0, 0, 0]` +Sets the velocity vector of the audio source or group. This controls both direction and speed in 3D space and is relative to the listener's velocity. The units are meters/second and are independent of position and orientation. +#### pannerAttr `Object` +Sets the panner node's attributes for a sound or group of sounds. See the `pannerAttr` method for all available options. + + +### Plugin: Global Effects Methods +#### pos(x, y, z) +Get/set the position of the listener in 3D cartesian space. Sounds using 3D position will be relative to the listener's position. +* **x**: `Number` The x-position of the listener. +* **y**: `Number` The y-position of the listener. +* **z**: `Number` The z-position of the listener. + +#### orientation(x, y, z, xUp, yUp, zUp) +Get/set the direction the listener is pointing in the 3D cartesian space. A front and up vector must be provided. The front is the direction the face of the listener is pointing, and up is the direction the top of the listener is pointing. Thus, these values are expected to be at right angles from each other. +* **x**: `Number` The x-orientation of listener. +* **y**: `Number` The y-orientation of listener. +* **z**: `Number` The z-orientation of listener. +* **xUp**: `Number` The x-orientation of the top of the listener. +* **yUp**: `Number` The y-orientation of the top of the listener. +* **zUp**: `Number` The z-orientation of the top of the listener. + +#### velocity(x, y, z) +Get/set the velocity vector of the listener. This controls both direction and speed in 3D space, and is combined relative to a sound's velocity to determine how much doppler shift (pitch change) to apply. +* **x**: `Number` The x-velocity of listener. +* **y**: `Number` The y-velocity of listener. +* **z**: `Number` The z-velocity of listener. + +#### pannerAttr(o) +Get/set the audio listener attributes. +* **o**: `Object` All values to update. + * **dopplerFactor** `1` Determines the amount of pitch shift from doppler effect. + * **speedOfSound** `343.3` Speed of sound used to calculate doppler shift. + + +### Mobile Playback +By default, audio on iOS, Android, etc is locked until a sound is played within a user interaction, and then it plays normally the rest of the page session ([Apple documentation](https://developer.apple.com/library/safari/documentation/audiovideo/conceptual/using_html5_audio_video/PlayingandSynthesizingSounds/PlayingandSynthesizingSounds.html)). The default behavior of howler.js is to attempt to silently unlock audio playback by playing an empty buffer on the first `touchend` event. This behavior can be disabled by calling: + +```javascript +Howler.mobileAutoEnable = false; +``` + +### Format Recommendations +Howler.js supports a wide array of audio codecs that have varying browser support ("mp3", "opus", "ogg", "wav", "aac", "m4a", "mp4", "weba", ...), but if you want full browser coverage you still need to use at least two of them. If your goal is to have the best balance of small filesize and high quality, based on extensive production testing, your best bet is to default to `ogg/webm` and fallback to `mp3`. Both `ogg` and `webm` have nearly full browser coverage with a great combination of compression and quality. You'll need the `mp3` fallback for Internet Explorer. + +It is important to remember that howler.js selects the first compatible sound from your array of sources. So if you want `ogg` or `webm` to be used before `mp3`, you need to put the sources in that order. + +### License + +Copyright (c) 2013-2015 James Simpson and GoldFire Studios, Inc. + +Released under the MIT License. \ No newline at end of file diff --git a/howler.js-2.0.0-beta4/bower.json b/howler.js-2.0.0-beta4/bower.json new file mode 100644 index 0000000..0ee4978 --- /dev/null +++ b/howler.js-2.0.0-beta4/bower.json @@ -0,0 +1,6 @@ +{ + "name": "howler.js", + "version": "2.0.0-beta4", + "description": "Javascript audio library for the modern web.", + "main": "howler.min.js" +} diff --git a/howler.js-2.0.0-beta4/howler.core.min.js b/howler.js-2.0.0-beta4/howler.core.min.js new file mode 100644 index 0000000..272bd61 --- /dev/null +++ b/howler.js-2.0.0-beta4/howler.core.min.js @@ -0,0 +1,2 @@ +/*! howler.js v2.0.0-beta4 | (c) 2013-2015, James Simpson of GoldFire Studios | MIT License | howlerjs.com */ +!function(){"use strict";function e(){try{"undefined"!=typeof AudioContext?n=new AudioContext:"undefined"!=typeof webkitAudioContext?n=new webkitAudioContext:o=!1}catch(e){o=!1}if(!o)if("undefined"!=typeof Audio)try{new Audio}catch(e){t=!0}else t=!0;try{var r=new Audio;r.muted&&(t=!0)}catch(e){}}var n=null,o=!0,t=!1;if(e(),o){var r="undefined"==typeof n.createGain?n.createGainNode():n.createGain();r.gain.value=1,r.connect(n.destination)}var d=function(){this.init()};d.prototype={init:function(){var e=this||u;return e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e.mobileAutoEnable=!0,e.noAudio=t,e.usingWebAudio=o,e.ctx=n,t||e._setupCodecs(),e},volume:function(e){var n=this||u;if(e=parseFloat(e),"undefined"!=typeof e&&e>=0&&1>=e){n._volume=e,o&&(r.gain.value=e);for(var t=0;t=0;n--)e._howls[n].unload();return e},codecs:function(e){return(this||u)._codecs[e]},_setupCodecs:function(){var e=this||u,n=new Audio,o=n.canPlayType("audio/mpeg;").replace(/^no$/,""),t=/OPR\//.test(navigator.userAgent);return e._codecs={mp3:!(t||!o&&!n.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!o,opus:!!n.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!n.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),aac:!!n.canPlayType("audio/aac;").replace(/^no$/,""),m4a:!!(n.canPlayType("audio/x-m4a;")||n.canPlayType("audio/m4a;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(n.canPlayType("audio/x-mp4;")||n.canPlayType("audio/mp4;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!!n.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),webm:!!n.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")},e},_enableMobileAudio:function(){var e=this||u,o=/iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk/i.test(navigator.userAgent),t=!!("ontouchend"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0);if(!n||!e._mobileEnabled&&o&&t){e._mobileEnabled=!1;var r=function(){var o=n.createBuffer(1,1,22050),t=n.createBufferSource();t.buffer=o,t.connect(n.destination),"undefined"==typeof t.start?t.noteOn(0):t.start(0),t.onended=function(){e._mobileEnabled=!0,e.mobileAutoEnable=!1,document.removeEventListener("touchend",r,!0)}};return document.addEventListener("touchend",r,!0),e}}};var u=new d,a=function(e){var n=this;return e.src&&0!==e.src.length?void n.init(e):void console.error("An array of source files must be passed with any new Howl.")};a.prototype={init:function(e){var t=this;return t._autoplay=e.autoplay||!1,t._ext=e.ext||null,t._html5=e.html5||!1,t._muted=e.mute||!1,t._loop=e.loop||!1,t._pool=e.pool||5,t._preload="boolean"==typeof e.preload?e.preload:!0,t._rate=e.rate||1,t._sprite=e.sprite||{},t._src="string"!=typeof e.src?e.src:[e.src],t._volume=void 0!==e.volume?e.volume:1,t._duration=0,t._loaded=!1,t._sounds=[],t._endTimers={},t._onend=e.onend?[{fn:e.onend}]:[],t._onfaded=e.onfaded?[{fn:e.onfaded}]:[],t._onload=e.onload?[{fn:e.onload}]:[],t._onloaderror=e.onloaderror?[{fn:e.onloaderror}]:[],t._onpause=e.onpause?[{fn:e.onpause}]:[],t._onplay=e.onplay?[{fn:e.onplay}]:[],t._onstop=e.onstop?[{fn:e.onstop}]:[],t._webAudio=o&&!t._html5,"undefined"!=typeof n&&n&&u.mobileAutoEnable&&u._enableMobileAudio(),u._howls.push(t),t._preload&&t.load(),t},load:function(){var e=this,n=null;if(t)return void e._emit("loaderror",null,"No audio support.");"string"==typeof e._src&&(e._src=[e._src]);for(var o=0;o0?i._seek:o._sprite[e][0]/1e3,s=(o._sprite[e][0]+o._sprite[e][1])/1e3-_,l=1e3*s/Math.abs(i._rate);o._endTimers[i._id]=setTimeout(o._ended.bind(o,i),l),i._paused=!1,i._ended=!1,i._sprite=e,i._seek=_,i._start=o._sprite[e][0]/1e3,i._stop=(o._sprite[e][0]+o._sprite[e][1])/1e3,i._loop=!(!i._loop&&!o._sprite[e][2]);var f=i._node;if(o._webAudio){var c=function(){o._refreshBuffer(i);var e=i._muted||o._muted?0:i._volume*u.volume();f.gain.setValueAtTime(e,n.currentTime),i._playStart=n.currentTime,"undefined"==typeof f.bufferSource.start?i._loop?f.bufferSource.noteGrainOn(0,_,86400):f.bufferSource.noteGrainOn(0,_,s):i._loop?f.bufferSource.start(0,_,86400):f.bufferSource.start(0,_,s),o._endTimers[i._id]||(o._endTimers[i._id]=setTimeout(o._ended.bind(o,i),l)),t[1]||setTimeout(function(){o._emit("play",i._id)},0)};o._loaded?c():(o.once("load",c),o._clearTimer(i._id))}else{var p=function(){f.currentTime=_,f.muted=i._muted||o._muted||u._muted||f.muted,f.volume=i._volume*u.volume(),f.playbackRate=i._rate,setTimeout(function(){f.play(),t[1]||o._emit("play",i._id)},0)};if(4===f.readyState||!f.readyState&&navigator.isCocoonJS)p();else{var m=function(){o._endTimers[i._id]=setTimeout(o._ended.bind(o,i),l),p(),f.removeEventListener("canplaythrough",m,!1)};f.addEventListener("canplaythrough",m,!1),o._clearTimer(i._id)}}return i._id},pause:function(e){var n=this;if(!n._loaded)return n.once("play",function(){n.pause(e)}),n;for(var o=n._getSoundIds(e),t=0;t=0?o=parseInt(r[0],10):e=parseFloat(r[0])}else r.length>=2&&(e=parseFloat(r[0]),o=parseInt(r[1],10));var i;if(!("undefined"!=typeof e&&e>=0&&1>=e))return i=o?t._soundById(o):t._sounds[0],i?i._volume:0;if(!t._loaded)return t.once("play",function(){t.volume.apply(t,r)}),t;"undefined"==typeof o&&(t._volume=e),o=t._getSoundIds(o);for(var _=0;_0?Math.ceil(1e3*(s-n.currentTime)):0)}.bind(d,u[a],i),t)}else{var l=Math.abs(e-o),f=e>o?"out":"in",c=l/.01,p=t/c;!function(){var n=e;i._interval=setInterval(function(e,t){n+="in"===f?.01:-.01,n=Math.max(0,n),n=Math.min(1,n),n=Math.round(100*n)/100,d.volume(n,e,!0),n===o&&(clearInterval(t._interval),delete t._interval,d._emit("faded",e))}.bind(d,u[a],i),p)}()}}return d},_stopFade:function(e){var o=this,t=o._soundById(e);return t._interval?(clearInterval(t._interval),delete t._interval,o._emit("faded",e)):t._timeout&&(clearTimeout(t._timeout),delete t._timeout,t._node.gain.cancelScheduledValues(n.currentTime),o._emit("faded",e)),o},loop:function(){var e,n,o,t=this,r=arguments;if(0===r.length)return t._loop;if(1===r.length){if("boolean"!=typeof r[0])return o=t._soundById(parseInt(r[0],10)),o?o._loop:!1;e=r[0],t._loop=e}else 2===r.length&&(e=r[0],n=parseInt(r[1],10));for(var d=t._getSoundIds(n),u=0;u=0?n=parseInt(t[0],10):e=parseFloat(t[0])}else 2===t.length&&(e=parseFloat(t[0]),n=parseInt(t[1],10));var u;if("number"!=typeof e)return u=o._soundById(n),u?u._rate:o._rate;if(!o._loaded)return o.once("load",function(){o.rate.apply(o,t)}),o;"undefined"==typeof n&&(o._rate=e),n=o._getSoundIds(n);for(var a=0;a=0?o=parseInt(r[0],10):(o=t._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),o=parseInt(r[1],10));if("undefined"==typeof o)return t;if(!t._loaded)return t.once("load",function(){t.seek.apply(t,r)}),t;var a=t._soundById(o);if(a){if(!(e>=0))return t._webAudio?a._seek+(t.playing(o)?n.currentTime-a._playStart:0):a._node.currentTime;var i=t.playing(o);i&&t.pause(o,!0),a._seek=e,t._clearTimer(o),i&&t.play(o,!0)}return t},playing:function(e){var n=this,o=n._soundById(e)||n._sounds[0];return o?!o._paused:!1},duration:function(){return this._duration},unload:function(){for(var e=this,n=e._sounds,o=0;o=0&&u._howls.splice(t,1)}return _&&delete _[e._src],e=null,null},on:function(e,n,o,t){var r=this,d=r["_on"+e];return"function"==typeof n&&d.push(t?{id:o,fn:n,once:t}:{id:o,fn:n}),r},off:function(e,n,o){var t=this,r=t["_on"+e];if(n){for(var d=0;d=0;t--){if(n>=o)return;e._sounds[t]._ended&&(e._webAudio&&e._sounds[t]._node&&e._sounds[t]._node.disconnect(0),e._sounds.splice(t,1),o--)}}},_getSoundIds:function(e){var n=this;if("undefined"==typeof e){for(var o=[],t=0;t>(-2*d&6)):0)o=t.indexOf(o);return a};for(var o=atob(n.split(",")[1]),t=new Uint8Array(o.length),r=0;r=0&&1>=e){n._volume=e,o&&(r.gain.value=e);for(var t=0;t=0;n--)e._howls[n].unload();return e},codecs:function(e){return(this||u)._codecs[e]},_setupCodecs:function(){var e=this||u,n=new Audio,o=n.canPlayType("audio/mpeg;").replace(/^no$/,""),t=/OPR\//.test(navigator.userAgent);return e._codecs={mp3:!(t||!o&&!n.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!o,opus:!!n.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!n.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),aac:!!n.canPlayType("audio/aac;").replace(/^no$/,""),m4a:!!(n.canPlayType("audio/x-m4a;")||n.canPlayType("audio/m4a;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(n.canPlayType("audio/x-mp4;")||n.canPlayType("audio/mp4;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!!n.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),webm:!!n.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")},e},_enableMobileAudio:function(){var e=this||u,o=/iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk/i.test(navigator.userAgent),t=!!("ontouchend"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0);if(!n||!e._mobileEnabled&&o&&t){e._mobileEnabled=!1;var r=function(){var o=n.createBuffer(1,1,22050),t=n.createBufferSource();t.buffer=o,t.connect(n.destination),"undefined"==typeof t.start?t.noteOn(0):t.start(0),t.onended=function(){e._mobileEnabled=!0,e.mobileAutoEnable=!1,document.removeEventListener("touchend",r,!0)}};return document.addEventListener("touchend",r,!0),e}}};var u=new d,a=function(e){var n=this;return e.src&&0!==e.src.length?void n.init(e):void console.error("An array of source files must be passed with any new Howl.")};a.prototype={init:function(e){var t=this;return t._autoplay=e.autoplay||!1,t._ext=e.ext||null,t._html5=e.html5||!1,t._muted=e.mute||!1,t._loop=e.loop||!1,t._pool=e.pool||5,t._preload="boolean"==typeof e.preload?e.preload:!0,t._rate=e.rate||1,t._sprite=e.sprite||{},t._src="string"!=typeof e.src?e.src:[e.src],t._volume=void 0!==e.volume?e.volume:1,t._duration=0,t._loaded=!1,t._sounds=[],t._endTimers={},t._onend=e.onend?[{fn:e.onend}]:[],t._onfaded=e.onfaded?[{fn:e.onfaded}]:[],t._onload=e.onload?[{fn:e.onload}]:[],t._onloaderror=e.onloaderror?[{fn:e.onloaderror}]:[],t._onpause=e.onpause?[{fn:e.onpause}]:[],t._onplay=e.onplay?[{fn:e.onplay}]:[],t._onstop=e.onstop?[{fn:e.onstop}]:[],t._webAudio=o&&!t._html5,"undefined"!=typeof n&&n&&u.mobileAutoEnable&&u._enableMobileAudio(),u._howls.push(t),t._preload&&t.load(),t},load:function(){var e=this,n=null;if(t)return void e._emit("loaderror",null,"No audio support.");"string"==typeof e._src&&(e._src=[e._src]);for(var o=0;o0?i._seek:o._sprite[e][0]/1e3,s=(o._sprite[e][0]+o._sprite[e][1])/1e3-_,l=1e3*s/Math.abs(i._rate);o._endTimers[i._id]=setTimeout(o._ended.bind(o,i),l),i._paused=!1,i._ended=!1,i._sprite=e,i._seek=_,i._start=o._sprite[e][0]/1e3,i._stop=(o._sprite[e][0]+o._sprite[e][1])/1e3,i._loop=!(!i._loop&&!o._sprite[e][2]);var f=i._node;if(o._webAudio){var c=function(){o._refreshBuffer(i);var e=i._muted||o._muted?0:i._volume*u.volume();f.gain.setValueAtTime(e,n.currentTime),i._playStart=n.currentTime,"undefined"==typeof f.bufferSource.start?i._loop?f.bufferSource.noteGrainOn(0,_,86400):f.bufferSource.noteGrainOn(0,_,s):i._loop?f.bufferSource.start(0,_,86400):f.bufferSource.start(0,_,s),o._endTimers[i._id]||(o._endTimers[i._id]=setTimeout(o._ended.bind(o,i),l)),t[1]||setTimeout(function(){o._emit("play",i._id)},0)};o._loaded?c():(o.once("load",c),o._clearTimer(i._id))}else{var p=function(){f.currentTime=_,f.muted=i._muted||o._muted||u._muted||f.muted,f.volume=i._volume*u.volume(),f.playbackRate=i._rate,setTimeout(function(){f.play(),t[1]||o._emit("play",i._id)},0)};if(4===f.readyState||!f.readyState&&navigator.isCocoonJS)p();else{var m=function(){o._endTimers[i._id]=setTimeout(o._ended.bind(o,i),l),p(),f.removeEventListener("canplaythrough",m,!1)};f.addEventListener("canplaythrough",m,!1),o._clearTimer(i._id)}}return i._id},pause:function(e){var n=this;if(!n._loaded)return n.once("play",function(){n.pause(e)}),n;for(var o=n._getSoundIds(e),t=0;t=0?o=parseInt(r[0],10):e=parseFloat(r[0])}else r.length>=2&&(e=parseFloat(r[0]),o=parseInt(r[1],10));var i;if(!("undefined"!=typeof e&&e>=0&&1>=e))return i=o?t._soundById(o):t._sounds[0],i?i._volume:0;if(!t._loaded)return t.once("play",function(){t.volume.apply(t,r)}),t;"undefined"==typeof o&&(t._volume=e),o=t._getSoundIds(o);for(var _=0;_0?Math.ceil(1e3*(s-n.currentTime)):0)}.bind(d,u[a],i),t)}else{var l=Math.abs(e-o),f=e>o?"out":"in",c=l/.01,p=t/c;!function(){var n=e;i._interval=setInterval(function(e,t){n+="in"===f?.01:-.01,n=Math.max(0,n),n=Math.min(1,n),n=Math.round(100*n)/100,d.volume(n,e,!0),n===o&&(clearInterval(t._interval),delete t._interval,d._emit("faded",e))}.bind(d,u[a],i),p)}()}}return d},_stopFade:function(e){var o=this,t=o._soundById(e);return t._interval?(clearInterval(t._interval),delete t._interval,o._emit("faded",e)):t._timeout&&(clearTimeout(t._timeout),delete t._timeout,t._node.gain.cancelScheduledValues(n.currentTime),o._emit("faded",e)),o},loop:function(){var e,n,o,t=this,r=arguments;if(0===r.length)return t._loop;if(1===r.length){if("boolean"!=typeof r[0])return o=t._soundById(parseInt(r[0],10)),o?o._loop:!1;e=r[0],t._loop=e}else 2===r.length&&(e=r[0],n=parseInt(r[1],10));for(var d=t._getSoundIds(n),u=0;u=0?n=parseInt(t[0],10):e=parseFloat(t[0])}else 2===t.length&&(e=parseFloat(t[0]),n=parseInt(t[1],10));var u;if("number"!=typeof e)return u=o._soundById(n),u?u._rate:o._rate;if(!o._loaded)return o.once("load",function(){o.rate.apply(o,t)}),o;"undefined"==typeof n&&(o._rate=e),n=o._getSoundIds(n);for(var a=0;a=0?o=parseInt(r[0],10):(o=t._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),o=parseInt(r[1],10));if("undefined"==typeof o)return t;if(!t._loaded)return t.once("load",function(){t.seek.apply(t,r)}),t;var a=t._soundById(o);if(a){if(!(e>=0))return t._webAudio?a._seek+(t.playing(o)?n.currentTime-a._playStart:0):a._node.currentTime;var i=t.playing(o);i&&t.pause(o,!0),a._seek=e,t._clearTimer(o),i&&t.play(o,!0)}return t},playing:function(e){var n=this,o=n._soundById(e)||n._sounds[0];return o?!o._paused:!1},duration:function(){return this._duration},unload:function(){for(var e=this,n=e._sounds,o=0;o=0&&u._howls.splice(t,1)}return _&&delete _[e._src],e=null,null},on:function(e,n,o,t){var r=this,d=r["_on"+e];return"function"==typeof n&&d.push(t?{id:o,fn:n,once:t}:{id:o,fn:n}),r},off:function(e,n,o){var t=this,r=t["_on"+e];if(n){for(var d=0;d=0;t--){if(n>=o)return;e._sounds[t]._ended&&(e._webAudio&&e._sounds[t]._node&&e._sounds[t]._node.disconnect(0),e._sounds.splice(t,1),o--)}}},_getSoundIds:function(e){var n=this;if("undefined"==typeof e){for(var o=[],t=0;t>(-2*d&6)):0)o=t.indexOf(o);return a};for(var o=atob(n.split(",")[1]),t=new Uint8Array(o.length),r=0;r (http://goldfirestudios.com)", + "repository": { + "type": "git", + "url": "git://github.com/goldfire/howler.js.git#2.0" + }, + "main": "howler.min.js", + "version": "2.0.0-beta4", + "license": { + "type": "MIT", + "url": "https://raw.githubusercontent.com/goldfire/howler.js/master/LICENSE.md" + }, + "files": [ + "src", + "howler.min.js", + "howler.core.min.js", + "howler.effects.min.js", + "LICENSE.md" + ] +} diff --git a/howler.js-2.0.0-beta4/src/howler.core.js b/howler.js-2.0.0-beta4/src/howler.core.js new file mode 100644 index 0000000..3cdd18b --- /dev/null +++ b/howler.js-2.0.0-beta4/src/howler.core.js @@ -0,0 +1,1808 @@ +/*! + * howler.js v2.0.0-beta4 + * howlerjs.com + * + * (c) 2013-2015, James Simpson of GoldFire Studios + * goldfirestudios.com + * + * MIT License + */ + +(function() { + + 'use strict'; + + // Setup our audio context. + var ctx = null; + var usingWebAudio = true; + var noAudio = false; + setupAudioContext(); + + // Create a master gain node. + if (usingWebAudio) { + var masterGain = (typeof ctx.createGain === 'undefined') ? ctx.createGainNode() : ctx.createGain(); + masterGain.gain.value = 1; + masterGain.connect(ctx.destination); + } + + /** Global Methods **/ + /***************************************************************************/ + + /** + * Create the global controller. All contained methods and properties apply + * to all sounds that are currently playing or will be in the future. + */ + var HowlerGlobal = function() { + this.init(); + }; + HowlerGlobal.prototype = { + /** + * Initialize the global Howler object. + * @return {Howler} + */ + init: function() { + var self = this || Howler; + + // Internal properties. + self._codecs = {}; + self._howls = []; + self._muted = false; + self._volume = 1; + + // Set to false to disable the auto iOS enabler. + self.mobileAutoEnable = true; + + // No audio is available on this system if this is set to true. + self.noAudio = noAudio; + + // This will be true if the Web Audio API is available. + self.usingWebAudio = usingWebAudio; + + // Expose the AudioContext when using Web Audio. + self.ctx = ctx; + + // Check for supported codecs. + if (!noAudio) { + self._setupCodecs(); + } + + return self; + }, + + /** + * Get/set the global volume for all sounds. + * @param {Float} vol Volume from 0.0 to 1.0. + * @return {Howler/Float} Returns self or current volume. + */ + volume: function(vol) { + var self = this || Howler; + vol = parseFloat(vol); + + if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) { + self._volume = vol; + + // When using Web Audio, we just need to adjust the master gain. + if (usingWebAudio) { + masterGain.gain.value = vol; + } + + // Loop through and change volume for all HTML5 audio nodes. + for (var i=0; i=0; i--) { + self._howls[i].unload(); + } + + return self; + }, + + /** + * Check for codec support of specific extension. + * @param {String} ext Audio file extention. + * @return {Boolean} + */ + codecs: function(ext) { + return (this || Howler)._codecs[ext]; + }, + + /** + * Check for browser support for various codecs and cache the results. + * @return {Howler} + */ + _setupCodecs: function() { + var self = this || Howler; + var audioTest = new Audio(); + var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, ''); + var isOpera = /OPR\//.test(navigator.userAgent); + + self._codecs = { + mp3: !!(!isOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))), + mpeg: !!mpegTest, + opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''), + ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), + wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''), + aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''), + m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), + mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), + weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), + webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '') + }; + + return self; + }, + + /** + * Mobile browsers will only allow audio to be played after a user interaction. + * Attempt to automatically unlock audio on the first user interaction. + * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/ + * @return {Howler} + */ + _enableMobileAudio: function() { + var self = this || Howler; + + // Only run this on iOS if audio isn't already eanbled. + var isMobile = /iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk/i.test(navigator.userAgent); + var isTouch = !!(('ontouchend' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)); + if (ctx && (self._mobileEnabled || !isMobile || !isTouch)) { + return; + } + + self._mobileEnabled = false; + + // Call this method on touch start to create and play a buffer, + // then check if the audio actually played to determine if + // audio has now been unlocked on iOS, Android, etc. + var unlock = function() { + // Create an empty buffer. + var buffer = ctx.createBuffer(1, 1, 22050); + var source = ctx.createBufferSource(); + source.buffer = buffer; + source.connect(ctx.destination); + + // Play the empty buffer. + if (typeof source.start === 'undefined') { + source.noteOn(0); + } else { + source.start(0); + } + + // Setup a timeout to check that we are unlocked on the next event loop. + source.onended = function() { + // Update the unlocked state and prevent this check from happening again. + self._mobileEnabled = true; + self.mobileAutoEnable = false; + + // Remove the touch start listener. + document.removeEventListener('touchend', unlock, true); + }; + }; + + // Setup a touch start listener to attempt an unlock in. + document.addEventListener('touchend', unlock, true); + + return self; + } + }; + + // Setup the global audio controller. + var Howler = new HowlerGlobal(); + + /** Group Methods **/ + /***************************************************************************/ + + /** + * Create an audio group controller. + * @param {Object} o Passed in properties for this group. + */ + var Howl = function(o) { + var self = this; + + // Throw an error if no source is provided. + if (!o.src || o.src.length === 0) { + console.error('An array of source files must be passed with any new Howl.'); + return; + } + + self.init(o); + }; + Howl.prototype = { + /** + * Initialize a new Howl group object. + * @param {Object} o Passed in properties for this group. + * @return {Howl} + */ + init: function(o) { + var self = this; + + // Setup user-defined default properties. + self._autoplay = o.autoplay || false; + self._ext = o.ext || null; + self._html5 = o.html5 || false; + self._muted = o.mute || false; + self._loop = o.loop || false; + self._pool = o.pool || 5; + self._preload = (typeof o.preload === 'boolean') ? o.preload : true; + self._rate = o.rate || 1; + self._sprite = o.sprite || {}; + self._src = (typeof o.src !== 'string') ? o.src : [o.src]; + self._volume = o.volume !== undefined ? o.volume : 1; + + // Setup all other default properties. + self._duration = 0; + self._loaded = false; + self._sounds = []; + self._endTimers = {}; + + // Setup event listeners. + self._onend = o.onend ? [{fn: o.onend}] : []; + self._onfaded = o.onfaded ? [{fn: o.onfaded}] : []; + self._onload = o.onload ? [{fn: o.onload}] : []; + self._onloaderror = o.onloaderror ? [{fn: o.onloaderror}] : []; + self._onpause = o.onpause ? [{fn: o.onpause}] : []; + self._onplay = o.onplay ? [{fn: o.onplay}] : []; + self._onstop = o.onstop ? [{fn: o.onstop}] : []; + + // Web Audio or HTML5 Audio? + self._webAudio = usingWebAudio && !self._html5; + + // Automatically try to enable audio on iOS. + if (typeof ctx !== 'undefined' && ctx && Howler.mobileAutoEnable) { + Howler._enableMobileAudio(); + } + + // Keep track of this Howl group in the global controller. + Howler._howls.push(self); + + // Load the source file unless otherwise specified. + if (self._preload) { + self.load(); + } + + return self; + }, + + /** + * Load the audio file. + * @return {Howler} + */ + load: function() { + var self = this; + var url = null; + + // If no audio is available, quit immediately. + if (noAudio) { + self._emit('loaderror', null, 'No audio support.'); + return; + } + + // Make sure our source is in an array. + if (typeof self._src === 'string') { + self._src = [self._src]; + } + + // Loop through the sources and pick the first one that is compatible. + for (var i=0; i 0 ? sound._seek : self._sprite[sprite][0] / 1000; + var duration = ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek; + + // Create a timer to fire at the end of playback or the start of a new loop. + var timeout = (duration * 1000) / Math.abs(sound._rate); + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + + // Update the parameters of the sound + sound._paused = false; + sound._ended = false; + sound._sprite = sprite; + sound._seek = seek; + sound._start = self._sprite[sprite][0] / 1000; + sound._stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000; + sound._loop = !!(sound._loop || self._sprite[sprite][2]); + + // Begin the actual playback. + var node = sound._node; + if (self._webAudio) { + // Fire this when the sound is ready to play to begin Web Audio playback. + var playWebAudio = function() { + self._refreshBuffer(sound); + + // Setup the playback params. + var vol = (sound._muted || self._muted) ? 0 : sound._volume * Howler.volume(); + node.gain.setValueAtTime(vol, ctx.currentTime); + sound._playStart = ctx.currentTime; + + // Play the sound using the supported method. + if (typeof node.bufferSource.start === 'undefined') { + sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration); + } else { + sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration); + } + + // Start a new timer if none is present. + if (!self._endTimers[sound._id]) { + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + } + + if (!args[1]) { + setTimeout(function() { + self._emit('play', sound._id); + }, 0); + } + }; + + if (self._loaded) { + playWebAudio(); + } else { + // Wait for the audio to load and then begin playback. + self.once('load', playWebAudio); + + // Cancel the end timer. + self._clearTimer(sound._id); + } + } else { + // Fire this when the sound is ready to play to begin HTML5 Audio playback. + var playHtml5 = function() { + node.currentTime = seek; + node.muted = sound._muted || self._muted || Howler._muted || node.muted; + node.volume = sound._volume * Howler.volume(); + node.playbackRate = sound._rate; + setTimeout(function() { + node.play(); + if (!args[1]) { + self._emit('play', sound._id); + } + }, 0); + }; + + // Play immediately if ready, or wait for the 'canplaythrough'e vent. + if (node.readyState === 4 || !node.readyState && navigator.isCocoonJS) { + playHtml5(); + } else { + var listener = function() { + // Setup the new end timer. + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + + // Begin playback. + playHtml5(); + + // Clear this listener. + node.removeEventListener('canplaythrough', listener, false); + }; + node.addEventListener('canplaythrough', listener, false); + + // Cancel the end timer. + self._clearTimer(sound._id); + } + } + + return sound._id; + }, + + /** + * Pause playback and save current position. + * @param {Number} id The sound ID (empty to pause all in group). + * @return {Howl} + */ + pause: function(id) { + var self = this; + + // Wait for the sound to begin playing before pausing it. + if (!self._loaded) { + self.once('play', function() { + self.pause(id); + }); + + return self; + } + + // If no id is passed, get all ID's to be paused. + var ids = self._getSoundIds(id); + + for (var i=0; i Returns the group's volume value. + * volume(id) -> Returns the sound id's current volume. + * volume(vol) -> Sets the volume of all sounds in this Howl group. + * volume(vol, id) -> Sets the volume of passed sound id. + * @return {Howl/Number} Returns self or current volume. + */ + volume: function() { + var self = this; + var args = arguments; + var vol, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // Return the value of the groups' volume. + return self._volume; + } else if (args.length === 1) { + // First check if this is an ID, and if not, assume it is a new volume. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else { + vol = parseFloat(args[0]); + } + } else if (args.length >= 2) { + vol = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // Update the volume or return the current volume. + var sound; + if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) { + // Wait for the sound to begin playing before changing the volume. + if (!self._loaded) { + self.once('play', function() { + self.volume.apply(self, args); + }); + + return self; + } + + // Set the group volume. + if (typeof id === 'undefined') { + self._volume = vol; + } + + // Update one or all volumes. + id = self._getSoundIds(id); + for (var i=0; i 0 ? Math.ceil((end - ctx.currentTime) * 1000) : 0); + }.bind(self, ids[i], sound), len); + } else { + var diff = Math.abs(from - to); + var dir = from > to ? 'out' : 'in'; + var steps = diff / 0.01; + var stepLen = len / steps; + + (function() { + var vol = from; + sound._interval = setInterval(function(id, sound) { + // Update the volume amount. + vol += (dir === 'in' ? 0.01 : -0.01); + + // Make sure the volume is in the right bounds. + vol = Math.max(0, vol); + vol = Math.min(1, vol); + + // Round to within 2 decimal points. + vol = Math.round(vol * 100) / 100; + + // Change the volume. + self.volume(vol, id, true); + + // When the fade is complete, stop it and fire event. + if (vol === to) { + clearInterval(sound._interval); + delete sound._interval; + self._emit('faded', id); + } + }.bind(self, ids[i], sound), stepLen); + })(); + } + } + } + + return self; + }, + + /** + * Internal method that stops the currently playing fade when + * a new fade starts, volume is changed or the sound is stopped. + * @param {Number} id The sound id. + * @return {Howl} + */ + _stopFade: function(id) { + var self = this; + var sound = self._soundById(id); + + if (sound._interval) { + clearInterval(sound._interval); + delete sound._interval; + self._emit('faded', id); + } else if (sound._timeout) { + clearTimeout(sound._timeout); + delete sound._timeout; + sound._node.gain.cancelScheduledValues(ctx.currentTime); + self._emit('faded', id); + } + + return self; + }, + + /** + * Get/set the loop parameter on a sound. This method can optionally take 0, 1 or 2 arguments. + * loop() -> Returns the group's loop value. + * loop(id) -> Returns the sound id's loop value. + * loop(loop) -> Sets the loop value for all sounds in this Howl group. + * loop(loop, id) -> Sets the loop value of passed sound id. + * @return {Howl/Boolean} Returns self or current loop value. + */ + loop: function() { + var self = this; + var args = arguments; + var loop, id, sound; + + // Determine the values for loop and id. + if (args.length === 0) { + // Return the grou's loop value. + return self._loop; + } else if (args.length === 1) { + if (typeof args[0] === 'boolean') { + loop = args[0]; + self._loop = loop; + } else { + // Return this sound's loop value. + sound = self._soundById(parseInt(args[0], 10)); + return sound ? sound._loop : false; + } + } else if (args.length === 2) { + loop = args[0]; + id = parseInt(args[1], 10); + } + + // If no id is passed, get all ID's to be looped. + var ids = self._getSoundIds(id); + for (var i=0; i Returns the first sound node's current playback rate. + * rate(id) -> Returns the sound id's current playback rate. + * rate(rate) -> Sets the playback rate of all sounds in this Howl group. + * rate(rate, id) -> Sets the playback rate of passed sound id. + * @return {Howl/Number} Returns self or the current playback rate. + */ + rate: function() { + var self = this; + var args = arguments; + var rate, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // We will simply return the current rate of the first node. + id = self._sounds[0]._id; + } else if (args.length === 1) { + // First check if this is an ID, and if not, assume it is a new rate value. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else { + rate = parseFloat(args[0]); + } + } else if (args.length === 2) { + rate = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // Update the playback rate or return the current value. + var sound; + if (typeof rate === 'number') { + // Wait for the sound to load before changing the playback rate. + if (!self._loaded) { + self.once('load', function() { + self.rate.apply(self, args); + }); + + return self; + } + + // Set the group rate. + if (typeof id === 'undefined') { + self._rate = rate; + } + + // Update one or all volumes. + id = self._getSoundIds(id); + for (var i=0; i Returns the first sound node's current seek position. + * seek(id) -> Returns the sound id's current seek position. + * seek(seek) -> Sets the seek position of the first sound node. + * seek(seek, id) -> Sets the seek position of passed sound id. + * @return {Howl/Number} Returns self or the current seek position. + */ + seek: function() { + var self = this; + var args = arguments; + var seek, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // We will simply return the current position of the first node. + id = self._sounds[0]._id; + } else if (args.length === 1) { + // First check if this is an ID, and if not, assume it is a new seek position. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else { + id = self._sounds[0]._id; + seek = parseFloat(args[0]); + } + } else if (args.length === 2) { + seek = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // If there is no ID, bail out. + if (typeof id === 'undefined') { + return self; + } + + // Wait for the sound to load before seeking it. + if (!self._loaded) { + self.once('load', function() { + self.seek.apply(self, args); + }); + + return self; + } + + // Get the sound. + var sound = self._soundById(id); + + if (sound) { + if (seek >= 0) { + // Pause the sound and update position for restarting playback. + var playing = self.playing(id); + if (playing) { + self.pause(id, true); + } + + // Move the position of the track and cancel timer. + sound._seek = seek; + self._clearTimer(id); + + // Restart the playback if the sound was playing. + if (playing) { + self.play(id, true); + } + } else { + if (self._webAudio) { + return (sound._seek + (self.playing(id) ? ctx.currentTime - sound._playStart : 0)); + } else { + return sound._node.currentTime; + } + } + } + + return self; + }, + + /** + * Check if a specific sound is currently playing or not. + * @param {Number} id The sound id to check. If none is passed, first sound is used. + * @return {Boolean} True if playing and false if not. + */ + playing: function(id) { + var self = this; + var sound = self._soundById(id) || self._sounds[0]; + + return sound ? !sound._paused : false; + }, + + /** + * Get the duration of this sound. + * @return {Number} Audio duration. + */ + duration: function() { + return this._duration; + }, + + /** + * Unload and destroy the current Howl object. + * This will immediately stop all sound instances attached to this group. + */ + unload: function() { + var self = this; + + // Stop playing any active sounds. + var sounds = self._sounds; + for (var i=0; i= 0) { + Howler._howls.splice(index, 1); + } + } + + // Delete this sound from the cache. + if (cache) { + delete cache[self._src]; + } + + // Clear out `self`. + self = null; + + return null; + }, + + /** + * Listen to a custom event. + * @param {String} event Event name. + * @param {Function} fn Listener to call. + * @param {Number} id (optional) Only listen to events for this sound. + * @param {Number} once (INTERNAL) Marks event to fire only once. + * @return {Howl} + */ + on: function(event, fn, id, once) { + var self = this; + var events = self['_on' + event]; + + if (typeof fn === 'function') { + events.push(once ? {id: id, fn: fn, once: once} : {id: id, fn: fn}); + } + + return self; + }, + + /** + * Remove a custom event. + * @param {String} event Event name. + * @param {Function} fn Listener to remove. Leave empty to remove all. + * @param {Number} id (optional) Only remove events for this sound. + * @return {Howl} + */ + off: function(event, fn, id) { + var self = this; + var events = self['_on' + event]; + + if (fn) { + // Loop through event store and remove the passed function. + for (var i=0; i=0; i--) { + if (cnt <= limit) { + return; + } + + if (self._sounds[i]._ended) { + // Disconnect the audio source when using Web Audio. + if (self._webAudio && self._sounds[i]._node) { + self._sounds[i]._node.disconnect(0); + } + + // Remove sounds until we have the pool size. + self._sounds.splice(i, 1); + cnt--; + } + } + }, + + /** + * Get all ID's from the sounds pool. + * @param {Number} id Only return one ID if one is passed. + * @return {Array} Array of IDs. + */ + _getSoundIds: function(id) { + var self = this; + + if (typeof id === 'undefined') { + var ids = []; + for (var i=0; i> (-2 * bc & 6)) : 0 + ) { + buffer = chars.indexOf(buffer); + } + + return output; + }; + + // Decode the base64 data URI without XHR, since some browsers don't support it. + var data = atob(url.split(',')[1]); + var dataView = new Uint8Array(data.length); + for (var i=0; i Returns the group's values. + * pannerAttr(id) -> Returns the sound id's values. + * pannerAttr(o) -> Set's the values of all sounds in this Howl group. + * pannerAttr(o, id) -> Set's the values of passed sound id. + * + * Attributes: + * coneInnerAngle - (360 by default) There will be no volume reduction inside this angle. + * coneOUterAngle - (360 by default) The volume will be reduced to a constant value of + * `coneOuterGain` outside this angle. + * coneOuterGain - (0 by default) The amount of volume reduction outside of `coneOuterAngle`. + * distanceModel - ('inverse' by default) Determines algorithm to use to reduce volume as audio moves + * away from listener. Can be `linear`, `inverse` or `exponential. + * maxDistance - (10000 by default) Volume won't reduce between source/listener beyond this distance. + * panningModel - ('HRTF' by default) Determines which spatialization algorithm is used to position audio. + * Can be `HRTF` or `equalpower`. + * refDistance - (1 by default) A reference distance for reducing volume as the source + * moves away from the listener. + * rolloffFactor - (1 by default) How quickly the volume reduces as source moves from listener. + * + * @return {Howl/Object} Returns self or current panner attributes. + */ + Howl.prototype.pannerAttr = function() { + var self = this; + var args = arguments; + var o, id, sound; + + // Stop right here if not using Web Audio. + if (!self._webAudio) { + return self; + } + + // Determine the values based on arguments. + if (args.length === 0) { + // Return the group's panner attribute values. + return self._pannerAttr; + } else if (args.length === 1) { + if (typeof args[0] === 'object') { + o = args[0]; + + // Set the grou's panner attribute values. + if (typeof id === 'undefined') { + self._pannerAttr = { + coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : self._coneInnerAngle, + coneOUterAngle: typeof o.coneOUterAngle !== 'undefined' ? o.coneOUterAngle : self._coneOUterAngle, + coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : self._coneOuterGain, + distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : self._distanceModel, + maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : self._maxDistance, + panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : self._panningModel, + refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : self._refDistance, + rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : self._rolloffFactor + }; + } + } else { + // Return this sound's panner attribute values. + sound = self._soundById(parseInt(args[0], 10)); + return sound ? sound._pannerAttr : self._pannerAttr; + } + } else if (args.length === 2) { + o = args[0]; + id = parseInt(args[1], 10); + } + + // Update the values of the specified sounds. + var ids = self._getSoundIds(id); + for (var i=0; i + + + + howler.js tests + + + +
+ + +
+ + + + \ No newline at end of file diff --git a/howler.js-2.0.0-beta4/tests/tests.js b/howler.js-2.0.0-beta4/tests/tests.js new file mode 100644 index 0000000..ff6479b --- /dev/null +++ b/howler.js-2.0.0-beta4/tests/tests.js @@ -0,0 +1,452 @@ +// Cache the label for later use. +var label = document.getElementById('label'); + +// Setup the sounds to be used. +var sound1 = new Howl({ + src: ['sound1.ogg', 'sound1.mp3'] +}); + +var sound2 = new Howl({ + src: ['sound1.ogg', 'sound1.mp3'], + html5: true +}); + +var sound3 = new Howl({ + src: ['sound2.ogg', 'sound2.mp3'], + sprite: { + one: [0, 450], + two: [2000, 250], + three: [4000, 350], + four: [6000, 380], + five: [8000, 340], + beat: [10000, 11163] + } +}); + +var sound4 = new Howl({ + src: ['sound2.ogg', 'sound2.mp3'], + html5: true, + sprite: { + one: [0, 450], + two: [2000, 250], + three: [4000, 350], + four: [6000, 380], + five: [8000, 340], + beat: [10000, 11163] + } +}); + +// Define the tests to run. +var id; +var webaudio = [ + function(fn) { + sound1.once('play', function() { + label.innerHTML = 'PLAYING'; + setTimeout(fn, 2000); + }); + + id = sound1.play(); + }, + + function(fn) { + sound1.pause(id); + + label.innerHTML = 'PAUSED'; + setTimeout(fn, 1500); + }, + + function(fn) { + sound1.play(id); + + label.innerHTML = 'RESUMING'; + setTimeout(fn, 2000); + }, + + function(fn) { + sound1.stop(id); + + label.innerHTML = 'STOPPED'; + setTimeout(fn, 1500); + }, + + function(fn) { + sound1.play(id); + + label.innerHTML = 'PLAY FROM START'; + setTimeout(fn, 2000); + }, + + function(fn) { + sound1.fade(1, 0, 2000, id); + + label.innerHTML = 'FADE OUT'; + sound1.once('faded', function() { + fn(); + }, id); + }, + + function(fn) { + sound1.fade(0, 1, 2000, id); + + label.innerHTML = 'FADE IN'; + sound1.once('faded', function() { + fn(); + }, id); + }, + + function(fn) { + sound1.mute(true, id); + + label.innerHTML = 'MUTE'; + setTimeout(fn, 1500); + }, + + function(fn) { + sound1.mute(false, id); + + label.innerHTML = 'UNMUTE'; + setTimeout(fn, 2000); + }, + + function(fn) { + sound1.volume(0.5, id); + + label.innerHTML = 'HALF VOLUME'; + setTimeout(fn, 2000); + }, + + function(fn) { + sound1.volume(1, id); + + label.innerHTML = 'FULL VOLUME'; + setTimeout(fn, 2000); + }, + + function(fn) { + sound1.seek(0, id); + + label.innerHTML = 'SEEK TO START'; + setTimeout(fn, 2000); + }, + + function(fn) { + id = sound1.play(); + + label.innerHTML = 'PLAY 2ND'; + setTimeout(fn, 2000); + }, + + function(fn) { + sound1.mute(true); + + label.innerHTML = 'MUTE GROUP'; + setTimeout(fn, 1500); + }, + + function(fn) { + sound1.mute(false); + + label.innerHTML = 'UNMUTE GROUP'; + setTimeout(fn, 2000); + }, + + function(fn) { + sound1.volume(0.5); + + label.innerHTML = 'HALF VOLUME GROUP'; + setTimeout(fn, 2000); + }, + + function(fn) { + sound1.fade(0.5, 0, 2000); + + label.innerHTML = 'FADE OUT GROUP'; + sound1.once('faded', function() { + if (sound1._onfaded.length === 0) { + fn(); + } + }); + }, + + function(fn) { + sound1.fade(0, 1, 2000); + + label.innerHTML = 'FADE IN GROUP'; + sound1.once('faded', function() { + if (sound1._onfaded.length === 0) { + fn(); + } + }); + }, + + function(fn) { + sound1.stop(); + + label.innerHTML = 'STOP GROUP'; + setTimeout(fn, 1500); + }, + + function(fn) { + id = sound3.play('beat'); + + label.innerHTML = 'PLAY SPRITE'; + setTimeout(fn, 2000); + }, + + function(fn) { + sound3.pause(id); + + label.innerHTML = 'PAUSE SPRITE'; + setTimeout(fn, 1000); + }, + + function(fn) { + sound3.play(id); + + label.innerHTML = 'RESUME SPRITE'; + setTimeout(fn, 1500); + }, + + function(fn) { + var sounds = ['one', 'two', 'three', 'four', 'five']; + for (var i=0; i + + + + viivaintegraalipeli + + + + + + + + + + + + + + + + +
Huom! 16.11. asianomistajan pyynnöstä grafiikkaa parannettu.
+ + \ No newline at end of file diff --git a/pixi.js b/pixi.js new file mode 100644 index 0000000..321d673 --- /dev/null +++ b/pixi.js @@ -0,0 +1,27488 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PIXI = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= arr.length) { + callback(); + } + } + } + }; + async.forEach = async.each; + + async.eachSeries = function (arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length) { + return callback(); + } + var completed = 0; + var iterate = function () { + iterator(arr[completed], function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(); + } + else { + iterate(); + } + } + }); + }; + iterate(); + }; + async.forEachSeries = async.eachSeries; + + async.eachLimit = function (arr, limit, iterator, callback) { + var fn = _eachLimit(limit); + fn.apply(null, [arr, iterator, callback]); + }; + async.forEachLimit = async.eachLimit; + + var _eachLimit = function (limit) { + + return function (arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length || limit <= 0) { + return callback(); + } + var completed = 0; + var started = 0; + var running = 0; + + (function replenish () { + if (completed >= arr.length) { + return callback(); + } + + while (running < limit && started < arr.length) { + started += 1; + running += 1; + iterator(arr[started - 1], function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + running -= 1; + if (completed >= arr.length) { + callback(); + } + else { + replenish(); + } + } + }); + } + })(); + }; + }; + + + var doParallel = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [async.each].concat(args)); + }; + }; + var doParallelLimit = function(limit, fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [_eachLimit(limit)].concat(args)); + }; + }; + var doSeries = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [async.eachSeries].concat(args)); + }; + }; + + + var _asyncMap = function (eachfn, arr, iterator, callback) { + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + if (!callback) { + eachfn(arr, function (x, callback) { + iterator(x.value, function (err) { + callback(err); + }); + }); + } else { + var results = []; + eachfn(arr, function (x, callback) { + iterator(x.value, function (err, v) { + results[x.index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + async.map = doParallel(_asyncMap); + async.mapSeries = doSeries(_asyncMap); + async.mapLimit = function (arr, limit, iterator, callback) { + return _mapLimit(limit)(arr, iterator, callback); + }; + + var _mapLimit = function(limit) { + return doParallelLimit(limit, _asyncMap); + }; + + // reduce only has a series version, as doing reduce in parallel won't + // work in many situations. + async.reduce = function (arr, memo, iterator, callback) { + async.eachSeries(arr, function (x, callback) { + iterator(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); + }; + // inject alias + async.inject = async.reduce; + // foldl alias + async.foldl = async.reduce; + + async.reduceRight = function (arr, memo, iterator, callback) { + var reversed = _map(arr, function (x) { + return x; + }).reverse(); + async.reduce(reversed, memo, iterator, callback); + }; + // foldr alias + async.foldr = async.reduceRight; + + var _filter = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.filter = doParallel(_filter); + async.filterSeries = doSeries(_filter); + // select alias + async.select = async.filter; + async.selectSeries = async.filterSeries; + + var _reject = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (!v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.reject = doParallel(_reject); + async.rejectSeries = doSeries(_reject); + + var _detect = function (eachfn, arr, iterator, main_callback) { + eachfn(arr, function (x, callback) { + iterator(x, function (result) { + if (result) { + main_callback(x); + main_callback = function () {}; + } + else { + callback(); + } + }); + }, function (err) { + main_callback(); + }); + }; + async.detect = doParallel(_detect); + async.detectSeries = doSeries(_detect); + + async.some = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (v) { + main_callback(true); + main_callback = function () {}; + } + callback(); + }); + }, function (err) { + main_callback(false); + }); + }; + // any alias + async.any = async.some; + + async.every = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (!v) { + main_callback(false); + main_callback = function () {}; + } + callback(); + }); + }, function (err) { + main_callback(true); + }); + }; + // all alias + async.all = async.every; + + async.sortBy = function (arr, iterator, callback) { + async.map(arr, function (x, callback) { + iterator(x, function (err, criteria) { + if (err) { + callback(err); + } + else { + callback(null, {value: x, criteria: criteria}); + } + }); + }, function (err, results) { + if (err) { + return callback(err); + } + else { + var fn = function (left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }; + callback(null, _map(results.sort(fn), function (x) { + return x.value; + })); + } + }); + }; + + async.auto = function (tasks, callback) { + callback = callback || function () {}; + var keys = _keys(tasks); + var remainingTasks = keys.length + if (!remainingTasks) { + return callback(); + } + + var results = {}; + + var listeners = []; + var addListener = function (fn) { + listeners.unshift(fn); + }; + var removeListener = function (fn) { + for (var i = 0; i < listeners.length; i += 1) { + if (listeners[i] === fn) { + listeners.splice(i, 1); + return; + } + } + }; + var taskComplete = function () { + remainingTasks-- + _each(listeners.slice(0), function (fn) { + fn(); + }); + }; + + addListener(function () { + if (!remainingTasks) { + var theCallback = callback; + // prevent final callback from calling itself if it errors + callback = function () {}; + + theCallback(null, results); + } + }); + + _each(keys, function (k) { + var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; + var taskCallback = function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + if (err) { + var safeResults = {}; + _each(_keys(results), function(rkey) { + safeResults[rkey] = results[rkey]; + }); + safeResults[k] = args; + callback(err, safeResults); + // stop subsequent errors hitting callback multiple times + callback = function () {}; + } + else { + results[k] = args; + async.setImmediate(taskComplete); + } + }; + var requires = task.slice(0, Math.abs(task.length - 1)) || []; + var ready = function () { + return _reduce(requires, function (a, x) { + return (a && results.hasOwnProperty(x)); + }, true) && !results.hasOwnProperty(k); + }; + if (ready()) { + task[task.length - 1](taskCallback, results); + } + else { + var listener = function () { + if (ready()) { + removeListener(listener); + task[task.length - 1](taskCallback, results); + } + }; + addListener(listener); + } + }); + }; + + async.retry = function(times, task, callback) { + var DEFAULT_TIMES = 5; + var attempts = []; + // Use defaults if times not passed + if (typeof times === 'function') { + callback = task; + task = times; + times = DEFAULT_TIMES; + } + // Make sure times is a number + times = parseInt(times, 10) || DEFAULT_TIMES; + var wrappedTask = function(wrappedCallback, wrappedResults) { + var retryAttempt = function(task, finalAttempt) { + return function(seriesCallback) { + task(function(err, result){ + seriesCallback(!err || finalAttempt, {err: err, result: result}); + }, wrappedResults); + }; + }; + while (times) { + attempts.push(retryAttempt(task, !(times-=1))); + } + async.series(attempts, function(done, data){ + data = data[data.length - 1]; + (wrappedCallback || callback)(data.err, data.result); + }); + } + // If a callback is passed, run this as a controll flow + return callback ? wrappedTask() : wrappedTask + }; + + async.waterfall = function (tasks, callback) { + callback = callback || function () {}; + if (!_isArray(tasks)) { + var err = new Error('First argument to waterfall must be an array of functions'); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + var wrapIterator = function (iterator) { + return function (err) { + if (err) { + callback.apply(null, arguments); + callback = function () {}; + } + else { + var args = Array.prototype.slice.call(arguments, 1); + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } + else { + args.push(callback); + } + async.setImmediate(function () { + iterator.apply(null, args); + }); + } + }; + }; + wrapIterator(async.iterator(tasks))(); + }; + + var _parallel = function(eachfn, tasks, callback) { + callback = callback || function () {}; + if (_isArray(tasks)) { + eachfn.map(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + eachfn.each(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.parallel = function (tasks, callback) { + _parallel({ map: async.map, each: async.each }, tasks, callback); + }; + + async.parallelLimit = function(tasks, limit, callback) { + _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); + }; + + async.series = function (tasks, callback) { + callback = callback || function () {}; + if (_isArray(tasks)) { + async.mapSeries(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + async.eachSeries(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.iterator = function (tasks) { + var makeCallback = function (index) { + var fn = function () { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + }; + fn.next = function () { + return (index < tasks.length - 1) ? makeCallback(index + 1): null; + }; + return fn; + }; + return makeCallback(0); + }; + + async.apply = function (fn) { + var args = Array.prototype.slice.call(arguments, 1); + return function () { + return fn.apply( + null, args.concat(Array.prototype.slice.call(arguments)) + ); + }; + }; + + var _concat = function (eachfn, arr, fn, callback) { + var r = []; + eachfn(arr, function (x, cb) { + fn(x, function (err, y) { + r = r.concat(y || []); + cb(err); + }); + }, function (err) { + callback(err, r); + }); + }; + async.concat = doParallel(_concat); + async.concatSeries = doSeries(_concat); + + async.whilst = function (test, iterator, callback) { + if (test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.whilst(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doWhilst = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + var args = Array.prototype.slice.call(arguments, 1); + if (test.apply(null, args)) { + async.doWhilst(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.until = function (test, iterator, callback) { + if (!test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.until(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doUntil = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + var args = Array.prototype.slice.call(arguments, 1); + if (!test.apply(null, args)) { + async.doUntil(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.queue = function (worker, concurrency) { + if (concurrency === undefined) { + concurrency = 1; + } + function _insert(q, data, pos, callback) { + if (!q.started){ + q.started = true; + } + if (!_isArray(data)) { + data = [data]; + } + if(data.length == 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + if (q.drain) { + q.drain(); + } + }); + } + _each(data, function(task) { + var item = { + data: task, + callback: typeof callback === 'function' ? callback : null + }; + + if (pos) { + q.tasks.unshift(item); + } else { + q.tasks.push(item); + } + + if (q.saturated && q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + var workers = 0; + var q = { + tasks: [], + concurrency: concurrency, + saturated: null, + empty: null, + drain: null, + started: false, + paused: false, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + kill: function () { + q.drain = null; + q.tasks = []; + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + if (!q.paused && workers < q.concurrency && q.tasks.length) { + var task = q.tasks.shift(); + if (q.empty && q.tasks.length === 0) { + q.empty(); + } + workers += 1; + var next = function () { + workers -= 1; + if (task.callback) { + task.callback.apply(task, arguments); + } + if (q.drain && q.tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + var cb = only_once(next); + worker(task.data, cb); + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + }, + idle: function() { + return q.tasks.length + workers === 0; + }, + pause: function () { + if (q.paused === true) { return; } + q.paused = true; + q.process(); + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + q.process(); + } + }; + return q; + }; + + async.priorityQueue = function (worker, concurrency) { + + function _compareTasks(a, b){ + return a.priority - b.priority; + }; + + function _binarySearch(sequence, item, compare) { + var beg = -1, + end = sequence.length - 1; + while (beg < end) { + var mid = beg + ((end - beg + 1) >>> 1); + if (compare(item, sequence[mid]) >= 0) { + beg = mid; + } else { + end = mid - 1; + } + } + return beg; + } + + function _insert(q, data, priority, callback) { + if (!q.started){ + q.started = true; + } + if (!_isArray(data)) { + data = [data]; + } + if(data.length == 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + if (q.drain) { + q.drain(); + } + }); + } + _each(data, function(task) { + var item = { + data: task, + priority: priority, + callback: typeof callback === 'function' ? callback : null + }; + + q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); + + if (q.saturated && q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + // Start with a normal queue + var q = async.queue(worker, concurrency); + + // Override push to accept second parameter representing priority + q.push = function (data, priority, callback) { + _insert(q, data, priority, callback); + }; + + // Remove unshift function + delete q.unshift; + + return q; + }; + + async.cargo = function (worker, payload) { + var working = false, + tasks = []; + + var cargo = { + tasks: tasks, + payload: payload, + saturated: null, + empty: null, + drain: null, + drained: true, + push: function (data, callback) { + if (!_isArray(data)) { + data = [data]; + } + _each(data, function(task) { + tasks.push({ + data: task, + callback: typeof callback === 'function' ? callback : null + }); + cargo.drained = false; + if (cargo.saturated && tasks.length === payload) { + cargo.saturated(); + } + }); + async.setImmediate(cargo.process); + }, + process: function process() { + if (working) return; + if (tasks.length === 0) { + if(cargo.drain && !cargo.drained) cargo.drain(); + cargo.drained = true; + return; + } + + var ts = typeof payload === 'number' + ? tasks.splice(0, payload) + : tasks.splice(0, tasks.length); + + var ds = _map(ts, function (task) { + return task.data; + }); + + if(cargo.empty) cargo.empty(); + working = true; + worker(ds, function () { + working = false; + + var args = arguments; + _each(ts, function (data) { + if (data.callback) { + data.callback.apply(null, args); + } + }); + + process(); + }); + }, + length: function () { + return tasks.length; + }, + running: function () { + return working; + } + }; + return cargo; + }; + + var _console_fn = function (name) { + return function (fn) { + var args = Array.prototype.slice.call(arguments, 1); + fn.apply(null, args.concat([function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (typeof console !== 'undefined') { + if (err) { + if (console.error) { + console.error(err); + } + } + else if (console[name]) { + _each(args, function (x) { + console[name](x); + }); + } + } + }])); + }; + }; + async.log = _console_fn('log'); + async.dir = _console_fn('dir'); + /*async.info = _console_fn('info'); + async.warn = _console_fn('warn'); + async.error = _console_fn('error');*/ + + async.memoize = function (fn, hasher) { + var memo = {}; + var queues = {}; + hasher = hasher || function (x) { + return x; + }; + var memoized = function () { + var args = Array.prototype.slice.call(arguments); + var callback = args.pop(); + var key = hasher.apply(null, args); + if (key in memo) { + async.nextTick(function () { + callback.apply(null, memo[key]); + }); + } + else if (key in queues) { + queues[key].push(callback); + } + else { + queues[key] = [callback]; + fn.apply(null, args.concat([function () { + memo[key] = arguments; + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, arguments); + } + }])); + } + }; + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + }; + + async.unmemoize = function (fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + }; + + async.times = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.map(counter, iterator, callback); + }; + + async.timesSeries = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.mapSeries(counter, iterator, callback); + }; + + async.seq = function (/* functions... */) { + var fns = arguments; + return function () { + var that = this; + var args = Array.prototype.slice.call(arguments); + var callback = args.pop(); + async.reduce(fns, args, function (newargs, fn, cb) { + fn.apply(that, newargs.concat([function () { + var err = arguments[0]; + var nextargs = Array.prototype.slice.call(arguments, 1); + cb(err, nextargs); + }])) + }, + function (err, results) { + callback.apply(that, [err].concat(results)); + }); + }; + }; + + async.compose = function (/* functions... */) { + return async.seq.apply(null, Array.prototype.reverse.call(arguments)); + }; + + var _applyEach = function (eachfn, fns /*args...*/) { + var go = function () { + var that = this; + var args = Array.prototype.slice.call(arguments); + var callback = args.pop(); + return eachfn(fns, function (fn, cb) { + fn.apply(that, args.concat([cb])); + }, + callback); + }; + if (arguments.length > 2) { + var args = Array.prototype.slice.call(arguments, 2); + return go.apply(this, args); + } + else { + return go; + } + }; + async.applyEach = doParallel(_applyEach); + async.applyEachSeries = doSeries(_applyEach); + + async.forever = function (fn, callback) { + function next(err) { + if (err) { + if (callback) { + return callback(err); + } + throw err; + } + fn(next); + } + next(); + }; + + // Node.js + if (typeof module !== 'undefined' && module.exports) { + module.exports = async; + } + // AMD / RequireJS + else if (typeof define !== 'undefined' && define.amd) { + define([], function () { + return async; + }); + } + // included directly via