UNPKG

audio-manager

Version:

Play sounds using Web Audio, fallback to HTML5 Audio

768 lines (660 loc) 42.2 kB
(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<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],2:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; (function () { try { cachedSetTimeout = setTimeout; } catch (e) { cachedSetTimeout = function () { throw new Error('setTimeout is not defined'); } } try { cachedClearTimeout = clearTimeout; } catch (e) { cachedClearTimeout = function () { throw new Error('clearTimeout is not defined'); } } } ()) var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = cachedSetTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; cachedClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { cachedSetTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],3:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],4:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // 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. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":3,"_process":2,"inherits":1}],5:[function(require,module,exports){ function AudioChannel(o){this.id=o,this.volume=1,this.muted=!0,this.loopSound=null,this.loopId=null,this.loopVol=0,this.nextLoop=null}module.exports=AudioChannel,AudioChannel.prototype.setVolume=function(o,t){var n=this.muted;this.muted=0===o||t||!1,void 0!==o&&null!==o?this.volume=o:o=this.volume,this.loopId&&(this.loopSound&&this.muted?this.loopSound.stop():this.loopSound&&this.loopSound.id===this.loopId?(this.loopSound.setVolume(Math.max(0,Math.min(1,o*this.loopVol))),n&&this.loopSound.play()):this.muted||this.audioManager.playLoopSound(this.id,this.loopId,this.loopVol))},AudioChannel.prototype.setMute=function(o){this.setVolume(null,o)},AudioChannel.prototype.playLoopSound=function(o,t,n,i,l,u){function e(o,t){return o?void(o.stopping||o.stop(function(){return h.freeSound(o),o=null,t&&t()})):t&&t()}function s(){var o=L.loopSound=L.nextLoop;L.nextLoop=null,o&&(o.setLoop(!0,l,u),o.fade=p,o.load(function(l){return l?(o.unload(),void(L.loopSound=null)):void o.play(t*L.volume,n,i)}))}function d(){L.loopSound=null,window.setTimeout(s,0)}var h=this.audioManager,p=h.settings.defaultFade,a=h.settings.crossFading,r=this.loopSound,m=r&&r.id;if(t=Math.max(0,Math.min(1,t||1)),this.loopId=o,this.loopVol=t,!h.muted&&!this.muted){if(o===m&&r)return r.play(t*this.volume,n,i),void(this.nextLoop&&(this.nextLoop.cancelOnLoadCallbacks(),this.nextLoop=null));if(r=null,!this.nextLoop||this.nextLoop.id!==o){var L=this;a?(this.nextLoop&&this.nextLoop.cancelOnLoadCallbacks(),this.nextLoop=h.createSound(o,this.id),this.nextLoop.load(function(o){return o?(L.nextLoop.unload(),void(L.nextLoop=null)):(e(L.loopSound),void d())})):(this.nextLoop=h.createSound(o,this.id),e(this.loopSound,d))}}}; },{}],6:[function(require,module,exports){ function AudioManager(o){this.soundsById={},this.soundGroupsById={},this.permanentSounds={},this.freeSoundPool=[],this.soundArchive=new OrderedList(function(){return 1}),this.soundGroupArchive=new OrderedList(function(){return 1}),this.soundArchiveById={},this.soundGroupArchiveById={},this.usedMemory=0,this.channels={},this.audioContext=null,this.muted=!1,this.settings={audioPath:"",maxSoundGroup:500,maxUsedMemory:300,defaultFade:2,maxPlayLatency:1e3,crossFading:!1,getFileUri:function(o,n){return o+n+".mp3"},getSoundConstructor:function(o,n){return null}};for(var n=0;n<o.length;n++){var e=o[n];this.channels[e]=new AudioChannel(e)}ISound.prototype.audioManager=this,SoundGroup.prototype.audioManager=this,AudioChannel.prototype.audioManager=this}var AudioContext=window.AudioContext||window.webkitAudioContext,OrderedList=require("./OrderedList"),SoundObject=require("./SoundBuffered.js"),SoundGroup=require("./SoundGroup.js"),AudioChannel=require("./AudioChannel.js"),ISound=require("./ISound.js");AudioContext||(console.warn("Web Audio API is not supported on this platform. Fallback to regular HTML5 <Audio>"),SoundObject=require("./Sound.js"),window.Audio||(console.warn("HTML5 <Audio> is not supported on this platform. Sound features are unavailable."),SoundObject=ISound));var NO_SOUND=new ISound;module.exports=AudioManager,module.exports.ISound=ISound,AudioManager.prototype.init=function(){if(!this.audioContext&&AudioContext){this.audioContext=new AudioContext,SoundObject.prototype.audioContext=this.audioContext;for(var o in this.soundsById)this.soundsById[o].init()}},AudioManager.prototype.getEmptySound=function(o,n){var e,t=this.settings.getSoundConstructor(o,n);return t?e=new t:(this.freeSoundPool.length>0?(e=this.freeSoundPool.pop(),e.init()):e=new SoundObject,e)},AudioManager.prototype.setup=function(o){for(var n in o){var e=o[n];this.setVolume(n,e.volume,e.muted)}},AudioManager.prototype.addChannel=function(o){this.channels[o]||(this.channels[o]=new AudioChannel(o))},AudioManager.prototype.setVolume=function(o,n,e){var t=this.channels[o];t&&t.setVolume(n,e)},AudioManager.prototype.setMute=function(o){void 0===o&&(o=!this.muted),this.muted=!!o;for(var n in this.channels){var e=this.channels[n];if(e.loopSound)if(o)e.loopSound.stop();else{var t=e.muted;e.muted=!0,e.setVolume(null,t)}}},AudioManager.prototype.loadSound=function(o,n){var e=this.createSound(o);return e.load(n),e},AudioManager.prototype.createSound=function(o,n){var e=this.getSound(o);return e?e:(e=this.soundsById[o]=this.getEmptySound(n,o),e.setId(o),e)},AudioManager.prototype.createSoundPermanent=function(o,n){var e=this.getSound(o);if(e)return e;var t=this.settings.getSoundConstructor(n,o)||SoundObject;return e=this.permanentSounds[o]=new t,e.setId(o),e},AudioManager.prototype.getSound=function(o){var n=this.permanentSounds[o];return n?n:(n=this.soundsById[o])?n:(n=this.soundArchiveById[o])?(this.soundArchive.removeByRef(n.poolRef),n.poolRef=null,delete this.soundArchiveById[o],this.soundsById[o]=n,n):null},AudioManager.prototype.getSoundGroup=function(o){var n=this.soundGroupsById[o];return n?n:(n=this.soundGroupArchiveById[o])?(this.soundGroupArchive.removeByRef(n.poolRef),n.poolRef=null,delete this.soundGroupArchiveById[o],n.verifySounds(),this.soundGroupsById[o]=n,n):null},AudioManager.prototype.freeSound=function(o){var n=o.id;this.soundsById[n]&&delete this.soundsById[n],this.soundArchiveById[n]&&(this.soundArchive.removeByRef(o.poolRef),o.poolRef=null,delete this.soundArchiveById[n]),o.unload(),o instanceof SoundObject&&this.freeSoundPool.push(o)},AudioManager.prototype.playLoopSound=function(o,n,e,t,u,i,r){var d=this.channels[o];return d?void d.playLoopSound(n,e,t,u,i,r):console.warn('Channel id "'+o+'" does not exist.')},AudioManager.prototype.stopLoopSound=function(o){var n=this,e=this.channels[o];if(!e)return console.warn('Channel id "'+o+'" does not exist.');var t=e.loopSound;e.loopId=null,t&&t.stop(function(){n.freeSound(t),e.loopSound=null})},AudioManager.prototype.stopAllLoopSounds=function(){for(var o in this.channels)this.stopLoopSound(o)},AudioManager.prototype.release=function(){var o,n,e,t=this.settings.maxSoundGroup,u=this.settings.maxUsedMemory,i={};for(o in this.channels){var r=this.channels[o];r.loopSound&&(i[r.loopSound.id]=!0)}for(o in this.soundGroupsById)n=this.soundGroupsById[o],n.poolRef=this.soundGroupArchive.add(n),this.soundGroupArchiveById[o]=n,delete this.soundGroupsById[o];for(o in this.soundsById)i[o]||(e=this.soundsById[o],e.poolRef=this.soundArchive.add(e),this.soundArchiveById[o]=e,delete this.soundsById[o]);for(var d=this.soundGroupArchive.getCount();d>t&&(n=this.soundGroupArchive.popFirst());)n.poolRef=null,delete this.soundGroupArchiveById[n.id],d-=1;for(;this.usedMemory>u&&(e=this.soundArchive.popFirst());)e.poolRef=null,delete this.soundArchiveById[e.id],this.freeSound(e)},AudioManager.prototype.playSound=function(o,n,e,t,u){if(this.muted)return NO_SOUND;var i=this.channels[o];if(i.muted)return NO_SOUND;var r=this.getSound(n);return r||(r=this.createSound(n,o)),e=e||1,r.play(i.volume*e,t,u),r},AudioManager.prototype.playSoundGroup=function(o,n,e,t,u){if(!this.muted){var i=this.channels[o];if(i&&!i.muted){var r=this.getSoundGroup(n);if(!r)return console.warn('SoundGroup "'+n+'" does not exist.');e=e||1,r.play(e*i.volume,t,u)}}},AudioManager.prototype.createSoundGroup=function(o,n,e){if(!this.getSoundGroup(o)){var t=new SoundGroup(o,n.id,n.vol,n.pitch,e);this.soundGroupsById[o]=t}},AudioManager.prototype.createSoundGroups=function(o,n){var e=void 0!==n&&this.channels[n].muted;for(var t in o)this.createSoundGroup(t,o[t],e)}; },{"./AudioChannel.js":5,"./ISound.js":7,"./OrderedList":8,"./Sound.js":9,"./SoundBuffered.js":10,"./SoundGroup.js":11}],7:[function(require,module,exports){ function ISound(){this.playing=!1,this.stopping=!1,this.fade=0,this.usedMemory=0,this.poolRef=null,this.onEnd=null,this.id=null,this.volume=1,this.pan=0,this.loop=!1,this.pitch=0,this._loaded=!1,this._loading=!1,this._unloading=!1,this._playTriggered=0,this._onLoadQueuedCallback=[]}module.exports=ISound,ISound.prototype.setId=function(t){this.id=t,this._loaded=!1},ISound.prototype.load=function(t){return this.id?this._loaded?t&&t(null,this):(t&&this._onLoadQueuedCallback.push(t),this._loading?void 0:(this._loading=!0,this._load())):t&&t("noId")},ISound.prototype._finalizeLoad=function(t){var o=this.audioManager.settings.maxPlayLatency;this._loaded=!t,this._loading=!1;for(var i=0;i<this._onLoadQueuedCallback.length;i++)this._onLoadQueuedCallback[i](t,this);return this._onLoadQueuedCallback=[],this._unloading?(this._unloading=!1,void this.unload()):void(this._loaded&&this._playTriggered&&((this.loop||Date.now()-this._playTriggered<o)&&this._play(),this._playTriggered=0))},ISound.prototype.cancelOnLoadCallbacks=function(){this._onLoadQueuedCallback=[]},ISound.prototype.play=function(t,o,i){return void 0!==t&&null!==t&&this.setVolume(t),void 0!==o&&null!==o&&this.setPan(o),this._loaded?this.loop&&this.playing?void this._updatePlayPitch(i):void this._play(i):(this._playTriggered=Date.now(),void this.load())},ISound.prototype.init=function(){},ISound.prototype.setVolume=function(t){this.volume=t},ISound.prototype.setPan=function(t){this.pan=t},ISound.prototype.setLoop=function(t){this.loop=t},ISound.prototype.setPitch=function(t){this.pitch=t},ISound.prototype._updatePlayPitch=function(t){},ISound.prototype._play=function(t){this.playing=!0,console.log('ISound play call: "'+this.id+'"')},ISound.prototype.stop=function(t){return this.playing=!1,t&&t()},ISound.prototype._load=function(){return console.log("ISound load call: "+this.id),this._finalizeLoad(null)},ISound.prototype.unload=function(){return this._playTriggered=0,this.setLoop(!1),this.fade=0,this.pitch=0,this.stop(),this._loading?(this._unloading=!0,!1):(this.audioManager.usedMemory-=this.usedMemory,this.setVolume(1),this.setPan(0),this.id=null,this._loaded=!1,this.usedMemory=0,!0)}; },{}],8:[function(require,module,exports){ function Node(t,e,i,s){this.object=t,this.previous=e,this.next=i,this.container=s}function OrderedList(t){this.count=0,this.first=null,this.last=null,this.cmpFunc=t}OrderedList.prototype.add=function(t){var e=new Node(t,null,null,this);if(this.count+=1,null===this.first)return this.first=e,this.last=e,e;var i=this.cmpFunc(t,this.first.object);if(i<0)return e.next=this.first,this.first.previous=e,this.first=e,e;var s=this.cmpFunc(t,this.last.object);if(s>=0)return e.previous=this.last,this.last.next=e,this.last=e,e;var r;if(i+s<0){for(r=this.first.next;this.cmpFunc(t,r.object)>=0;)r=r.next;e.next=r,e.previous=r.previous,e.previous.next=e,r.previous=e}else{for(r=this.last.previous;this.cmpFunc(t,r.object)<0;)r=r.previous;e.previous=r,e.next=r.next,e.next.previous=e,r.next=e}return e},OrderedList.prototype.removeByRef=function(t){return!(!t||t.container!==this)&&(this.count-=1,null===t.previous?this.first=t.next:t.previous.next=t.next,null===t.next?this.last=t.previous:t.next.previous=t.previous,t.previous=null,t.next=null,t.container=null,!0)},OrderedList.prototype.moveToTheBeginning=function(t){return!(!t||t.container!==this)&&(null===t.previous||(t.previous.next=t.next,this.last===t?this.last=t.previous:t.next.previous=t.previous,t.previous=null,t.next=this.first,t.next.previous=t,this.first=t,!0))},OrderedList.prototype.moveToTheEnd=function(t){return!(!t||t.container!==this)&&(null===t.next||(t.next.previous=t.previous,this.first===t?this.first=t.next:t.previous.next=t.next,t.next=null,t.previous=this.last,t.previous.next=t,this.last=t,!0))},OrderedList.prototype.possess=function(t){return t&&t.container===this},OrderedList.prototype.popFirst=function(){var t=this.first;if(!t)return null;this.count-=1;var e=t.object;return this.first=t.next,null!==this.first&&(this.first.previous=null),t.next=null,t.container=null,e},OrderedList.prototype.popLast=function(){var t=this.last;if(!t)return null;this.count-=1;var e=t.object;return this.last=t.previous,null!==this.last&&(this.last.next=null),t.previous=null,t.container=null,e},OrderedList.prototype.getFirst=function(){return this.first&&this.first.object},OrderedList.prototype.getLast=function(){return this.last&&this.last.object},OrderedList.prototype.clear=function(){for(var t=this.first;t;t=t.next)t.container=null;this.count=0,this.first=null,this.last=null},OrderedList.prototype.getCount=function(){return this.count},OrderedList.prototype.forEach=function(t,e){for(var i=this.first;i;i=i.next)t(i.object,e)},OrderedList.prototype.forEachReverse=function(t,e){for(var i=this.last;i;i=i.previous)t(i.object,e)},OrderedList.prototype.reposition=function(t){if(t.container!==this)return this.add(t.object);var e=t.previous,i=t.next,s=t.object;for(null===i?this.last=e:i.previous=e,null===e?this.first=i:e.next=i;null!==e&&this.cmpFunc(s,e.object)<0;)i=e,e=e.previous;for(;null!==i&&this.cmpFunc(s,i.object)>=0;)e=i,i=i.next;return t.next=i,null===i?this.last=t:i.previous=t,t.previous=e,null===e?this.first=t:e.next=t,t},module.exports=OrderedList; },{}],9:[function(require,module,exports){ function Sound(){ISound.call(this);var i=new Audio;i.loop=!1,i.type="audio/mpeg",this._audio=i,this._onEnd=null,this.audioContext&&(this.source=this.audioContext.createMediaElementSource(i),this.source.connect(this.audioContext.destination))}var inherits=require("util").inherits,ISound=require("./ISound.js"),PLAY_OPTIONS={playAudioWhenScreenIsLocked:!1};inherits(Sound,ISound),module.exports=Sound,Sound.prototype.setVolume=function(i){this.volume=this._audio.volume=i},Sound.prototype.setLoop=function(i){this.loop=this._audio.loop=i},Sound.prototype._load=function(){function i(i){e._finalizeLoad(i)}function o(){this.removeEventListener("canplaythrough",o),this.removeEventListener("error",t),e.usedMemory=this.duration,e.audioManager.usedMemory+=this.duration,e._finalizeLoad(null)}function t(n){this.removeEventListener("canplaythrough",o),this.removeEventListener("error",t),i(n)}function n(i){e._loading=!0,e._audio.addEventListener("canplaythrough",o),e._audio.addEventListener("error",t),e._audio.src=i,e._audio.load()}var e=this,u=this.audioManager.settings.getFileUri,a=this.audioManager.settings.audioPath;if(u.length>2)u(a,this.id,function(o,t){return o?i(o):void n(t)});else try{var d=u(a,this.id);if(!d)return i("emptyUri");n(d)}catch(o){i(o)}},Sound.prototype.unload=function(){ISound.prototype.unload.call(this)&&(this._audio.volume=1,this._audio.src="",this._audio.load())},Sound.prototype._play=function(i){if(this._audio.volume=this.volume,this._audio.pause(),this._audio.currentTime=0,this._audio.play(PLAY_OPTIONS),this.playing=!0,!this.loop){var o=1e3*this._audio.duration;if(!(isNaN(o)||o<=0)){var t=this;this._onEnd=window.setTimeout(function(){t._onEnd=null,t._playing=!1,t.onEnd&&t.onEnd()},o)}}},Sound.prototype.stop=function(i){return null!==this._onEnd&&(window.clearTimeout(this._onEnd),this._onEnd=null),this._audio.pause(),this._audio.currentTime=0,this._playTriggered=0,this.playing=!1,i&&i()}; },{"./ISound.js":7,"util":4}],10:[function(require,module,exports){ function SoundBuffered(){ISound.call(this),this.buffer=null,this.source=null,this.sourceConnector=null,this.gain=null,this.panNode=null,this.rawAudioData=null,this._playPitch=0,this._fadeTimeout=null,this._onStopCallback=null,this._audioNodeReady=!1,this._loopStart=0,this._loopEnd=0,this.init()}var inherits=require("util").inherits,ISound=require("./ISound.js"),MIN_VALUE=1e-6;inherits(SoundBuffered,ISound),module.exports=SoundBuffered,SoundBuffered.prototype._createAudioNodes=function(){if(!this._audioNodeReady&&this.audioContext){var t,e=this.audioContext,i=e.createGain();t=e.createStereoPanner?e.createStereoPanner():e.createPanner(),i.connect(t),t.connect(e.destination),i.gain.value=0,this.sourceConnector=i,this.gain=i.gain,this.panNode=t,this._audioNodeReady=!0}},SoundBuffered.prototype._destroyAudioNodes=function(){if(this._audioNodeReady){var t=this.audioContext,e=this.panNode,i=this.sourceConnector;i.disconnect(e),e.disconnect(t.destination),this.source&&(this.source.disconnect(i),this.source.onended=null,this.source=null),this.sourceConnector=null,this.gain=null,this.panNode=null,this.rawAudioData=null,this._audioNodeReady=!1}},SoundBuffered.prototype.init=function(){function t(t){i.buffer=t,i.usedMemory=t.duration,i.audioManager.usedMemory+=t.duration,i.rawAudioData=null,i._loaded&&i._playTriggered&&((i.loop||Date.now()-i._playTriggered<o)&&i._play(),i._playTriggered=0)}function e(){console.error("decode audio failed for sound ",i.id)}if(this._createAudioNodes(),this.rawAudioData){var i=this,o=this.audioManager.settings.maxPlayLatency,n=this.audioContext;n.decodeAudioData(this.rawAudioData,t,e)}},SoundBuffered.prototype.setVolume=function(t){if(this.volume=t,this.playing){if(!this.fade)return void(this.gain.value=t);t<=0&&(t=MIN_VALUE);var e=this.audioContext.currentTime;this.gain.cancelScheduledValues(e),this.gain.setValueAtTime(this.gain.value||MIN_VALUE,e),this.gain.linearRampToValueAtTime(t,e+this.fade)}},SoundBuffered.prototype.setPan=function(t){this.pan=t,this.panNode&&(this.panNode.pan?this.panNode.pan.value=t:this.panNode.setPosition(t,0,.2))},SoundBuffered.prototype.setLoop=function(t,e,i){this.loop=!!t,this._loopStart=e||0,this._loopEnd=i||0,this.source&&this.buffer&&(this.source.loop=t,this._setLoopPoints())},SoundBuffered.prototype._setLoopPoints=function(){this.source.loopStart=this._loopStart||0;var t=this._loopEnd;t<0&&(t=this.buffer.duration+t),t<0&&(t=0),this.source.loopEnd=t||this.buffer.duration},SoundBuffered.prototype.setPitch=function(t,e){this.pitch=t,this._setPlaybackRate(e)},SoundBuffered.prototype._updatePlayPitch=function(t){!t&&0!==t||t===this._playPitch||(this._playPitch=t,this._setPlaybackRate(0))},SoundBuffered.prototype._setPlaybackRate=function(t){if(this.source){var e=Math.pow(2,(this._playPitch+this.pitch)/12);if(!t)return void(this.source.playbackRate.value=e);var i=this.audioContext.currentTime;this.source.playbackRate.cancelScheduledValues(i),this.source.playbackRate.setValueAtTime(this.source.playbackRate.value||MIN_VALUE,i),this.source.playbackRate.linearRampToValueAtTime(e,i+t)}},SoundBuffered.prototype._load=function(){function t(t){o._finalizeLoad(t)}function e(t){o.buffer=t,o.usedMemory=t.duration,o.audioManager.usedMemory+=t.duration,o._finalizeLoad(null)}function i(i){var n=new XMLHttpRequest;n.responseType="arraybuffer",n.onreadystatechange=function(){if(4===~~n.readyState)return 200!==~~n.status&&0!==~~n.status?t("xhrError:"+n.status):void(o.audioContext?o.audioContext.decodeAudioData(n.response,e,t):(o.rawAudioData=n.response,o._finalizeLoad(null)))},n.open("GET",i,!0),n.send()}var o=this;this._createAudioNodes();var n=this.audioManager.settings.getFileUri,a=this.audioManager.settings.audioPath;if(n.length>2)n(a,this.id,function(e,o){return e?t(e):void i(o)});else try{var s=n(a,this.id);if(!s)return t("emptyUri");i(s)}catch(e){t(e)}},SoundBuffered.prototype.unload=function(){ISound.prototype.unload.call(this)&&(this._fadeTimeout&&(this._onStopCallback=null,this._stopAndClear()),this.buffer=null,this.source&&(this.source.onended=null,this.source.stop(0),this.source=null),this._destroyAudioNodes())},SoundBuffered.prototype._play=function(t){if(!this.buffer)return void(this._playTriggered=Date.now());this.playing=!0;var e=this.audioContext.currentTime;if(this.gain.cancelScheduledValues(e),this.fade?(this.gain.setValueAtTime(this.gain.value||MIN_VALUE,e),this.gain.linearRampToValueAtTime(this.volume||MIN_VALUE,e+this.fade)):this.gain.value=this.volume,this._fadeTimeout)return this._onStopCallback=null,this.source.onended=null,this.stopping=!1,window.clearTimeout(this._fadeTimeout),void(this._fadeTimeout=null);this.source&&(this.source.disconnect(this.sourceConnector),this.source.onended=null);var i=this.source=this.audioContext.createBufferSource();i.connect(this.sourceConnector);var o=this;i.onended=function(){o.playing=!1,i.onended=null,o.source=null,o.onEnd&&o.onEnd()},this._playPitch=t||0,(t||this.pitch)&&this._setPlaybackRate(0),i.loop=this.loop,i.buffer=this.buffer,this._setLoopPoints(),i.start(0)},SoundBuffered.prototype._stopAndClear=function(){this.stopping=!1,this.source.onended=null,this.source.stop(0),this.source=null,this._fadeTimeout&&(window.clearTimeout(this._fadeTimeout),this._fadeTimeout=null),this._onStopCallback&&(this._onStopCallback(),this._onStopCallback=null)},SoundBuffered.prototype.stop=function(t){if(!this.playing&&!this.stopping)return t&&t();if(this._playTriggered=0,this.stopping=!0,this.playing=!1,!this.source)return t&&t();if(this._onStopCallback=t,!this._fadeTimeout){if(this.fade){var e=this,i=this.audioContext.currentTime;return this.gain.cancelScheduledValues(i),this.gain.setValueAtTime(this.gain.value||MIN_VALUE,i),this.gain.linearRampToValueAtTime(MIN_VALUE,i+this.fade),void(this._fadeTimeout=window.setTimeout(function(){e._fadeTimeout=null,e._stopAndClear()},1e3*this.fade))}this._stopAndClear()}}; },{"./ISound.js":7,"util":4}],11:[function(require,module,exports){ function SoundGroup(s,t,o,i,n){this.id=s,this.soundIds=t,this.volumes=o||[],this.pitches=i||[],this.soundIndex=0,this.volIndex=0,this.pitchIndex=0,this.poolRef=null,this._ready=!1,0===this.volumes.length&&this.volumes.push(1),0===this.pitches.length&&this.pitches.push(0),n||this._createSounds()}module.exports=SoundGroup,SoundGroup.prototype._createSounds=function(){for(var s=this.soundIds,t=0;t<s.length;t++)this.audioManager.loadSound(s[t]);this._ready=!0},SoundGroup.prototype.play=function(s,t,o){if(0!==this.soundIds.length){this._ready||this._createSounds();var i=this.soundIds[this.soundIndex++],n=this.audioManager.getSound(i);if(!n)return console.warn("[Sound Group: "+this.id+"] sound id "+i+" cannot be played.");s=s||1,o=o||0,s*=this.volumes[this.volIndex++],o+=this.pitches[this.pitchIndex++],n.play(s,t,o),this.soundIndex>=this.soundIds.length&&(this.soundIndex=0),this.volIndex>=this.volumes.length&&(this.volIndex=0),this.pitchIndex>=this.pitches.length&&(this.pitchIndex=0)}},SoundGroup.prototype.verifySounds=function(){for(var s=0;s<this.soundIds.length;s++){var t=this.soundIds[s];this.audioManager.createSound(t)}}; },{}],12:[function(require,module,exports){ AudioManager=require("./AudioManager.js"); },{"./AudioManager.js":6}]},{},[12]);