@eva/plugin-sound 2.0.0-beta.2 → 2.0.0-beta.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/EVA.plugin.sound.js +1656 -223
- package/dist/EVA.plugin.sound.min.js +1 -1
- package/dist/plugin-sound.cjs.js +54 -227
- package/dist/plugin-sound.cjs.prod.js +3 -2
- package/dist/plugin-sound.d.ts +9 -28
- package/dist/plugin-sound.esm.js +54 -227
- package/package.json +5 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
function _extends(){return _extends=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)({}).hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t},_extends.apply(null,arguments)}window.EVA=window.EVA||{},window.EVA.plugin=window.EVA.plugin||{};var _EVA_IIFE_sound=function(t,e){"use strict";function i(t,e,i,s){return new(i||(i=Promise))((function(o,n){function r(t){try{a(s.next(t))}catch(t){n(t)}}function d(t){try{a(s.throw(t))}catch(t){n(t)}}function a(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(r,d)}a((s=s.apply(t,e||[])).next())}))}let s=class extends e.System{constructor(t){super(),this.autoPauseAndStart=!0,this.components=[],this.pausedComponents=[],this.audioBufferCache={},this.decodeAudioPromiseMap={},_extends(this,t)}get muted(){return!!this.gainNode&&0===this.gainNode.gain.value}set muted(t){this.gainNode&&this.gainNode.gain.setValueAtTime(t?0:1,0)}get volume(){return this.gainNode?this.gainNode.gain.value:1}set volume(t){!this.gainNode||"number"!=typeof t||t<0||t>1||this.gainNode.gain.setValueAtTime(t,0)}get audioLocked(){return!this.ctx||"running"!==this.ctx.state}resumeAll(){const t=()=>{this.pausedComponents.forEach((t=>{t.play()})),this.pausedComponents=[]};this.ctx.resume().then(t,t)}pauseAll(){this.components.forEach((t=>{t.playing&&(this.pausedComponents.push(t),t.pause())})),this.ctx.suspend().then()}stopAll(){this.components.forEach((t=>{t.playing&&t.stop()})),this.pausedComponents=[],this.ctx.suspend().then()}init(){this.setupAudioContext()}update(){const t=this.componentObserver.clear();for(const e of t)this.componentChanged(e)}onResume(){this.autoPauseAndStart&&this.resumeAll()}onPause(){this.autoPauseAndStart&&this.pauseAll()}onDestroy(){this.components.forEach((t=>{t.onDestroy()})),this.components=[],this.ctx&&(this.gainNode.disconnect(),this.gainNode=null,this.ctx.close(),this.ctx=null)}componentChanged(t){return i(this,void 0,void 0,(function*(){"Sound"===t.componentName&&t.type===e.OBSERVER_TYPE.ADD&&this.add(t)}))}setupAudioContext(){try{const t=window.AudioContext||window.webkitAudioContext;this.ctx=new t}catch(t){console.error(t),this.onError&&this.onError(t)}this.ctx&&(this.gainNode=void 0===this.ctx.createGain?this.ctx.createGainNode():this.ctx.createGain(),this.gainNode.gain.setValueAtTime(this.muted?0:this.volume,this.ctx.currentTime),this.gainNode.connect(this.ctx.destination),this.unlockAudio())}unlockAudio(){if(!this.ctx||!this.audioLocked)return;const t=()=>{if(this.ctx){const e=()=>{document.body.removeEventListener("touchstart",t),document.body.removeEventListener("touchend",t),document.body.removeEventListener("click",t)};this.ctx.resume().then(e,e)}};document.body.addEventListener("touchstart",t),document.body.addEventListener("touchend",t),document.body.addEventListener("click",t)}add(t){var s;return i(this,void 0,void 0,(function*(){const i=t.component;this.components.push(i);try{const{config:t}=i;i.state="loading";const o=yield e.resource.getResource(t.resource);!this.audioBufferCache[o.name]&&(null===(s=null==o?void 0:o.data)||void 0===s?void 0:s.audio)&&(this.audioBufferCache[o.name]=yield this.decodeAudioData(o.data.audio,o.name)),this.audioBufferCache[o.name]&&(i.systemContext=this.ctx,i.systemDestination=this.gainNode,i.onload(this.audioBufferCache[o.name]))}catch(t){this.onError&&this.onError(t)}}))}decodeAudioData(t,e){if(this.decodeAudioPromiseMap[e])return this.decodeAudioPromiseMap[e];const i=new Promise(((i,s)=>{this.ctx||s(new Error("No audio support"));const o=this.ctx.decodeAudioData(t,(t=>{this.decodeAudioPromiseMap[e]&&delete this.decodeAudioPromiseMap[e],t?i(t):s(new Error(`Error decoding audio ${e}`))}),(i=>{this.decodeAudioPromiseMap[e]&&delete this.decodeAudioPromiseMap[e],s(new Error(`${i}. arrayBuffer byteLength: ${t?t.byteLength:0}`))}));o instanceof Promise&&o.catch((e=>{s(new Error(`catch ${e}, arrayBuffer byteLength: ${t?t.byteLength:0}`))}))}));return this.decodeAudioPromiseMap[e]=i,i}};s.systemName="SoundSystem",s=function(t,e,i,s){var o,n=arguments.length,r=n<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(t,e,i,s);else for(var d=t.length-1;d>=0;d--)(o=t[d])&&(r=(n<3?o(r):n>3?o(e,i,r):o(e,i))||r);return n>3&&r&&Object.defineProperty(e,i,r),r}([e.decorators.componentObserver({Sound:[]})],s);var o=s;class n extends e.Component{constructor(){super(...arguments),this.state="unloaded",this.config={resource:"",autoplay:!1,muted:!1,volume:1,loop:!1,seek:0},this.playTime=0,this.startTime=0,this.duration=0,this.actionQueue=[]}get muted(){return!!this.gainNode&&0===this.gainNode.gain.value}set muted(t){this.gainNode&&this.gainNode.gain.setValueAtTime(t?0:this.config.volume,0)}get volume(){return this.gainNode?this.gainNode.gain.value:1}set volume(t){"number"!=typeof t||t<0||t>1||(this.config.volume=t,this.gainNode&&this.gainNode.gain.setValueAtTime(t,0))}init(t){t&&(_extends(this.config,t),this.config.autoplay&&this.actionQueue.push(this.play.bind(this)))}play(){if("loaded"!==this.state&&this.actionQueue.push(this.play.bind(this)),this.destroySource(),this.createSource(),!this.sourceNode)return;const t=this.systemContext.currentTime,e=this.config.seek,i=this.config.duration;this.sourceNode.start(0,e,i),this.startTime=t,this.playTime=t-e,this.paused=!1,this.playing=!0,this.resetConfig(),this.endedListener=()=>{this.sourceNode&&(this.config.onEnd&&this.config.onEnd(),this.playing&&this.destroySource())},this.sourceNode.addEventListener("ended",this.endedListener)}pause(){"loaded"!==this.state&&this.actionQueue.push(this.pause.bind(this)),!this.paused&&this.playing&&(this.paused=!0,this.playing=!1,this.config.seek=this.getCurrentTime(),this.destroySource())}stop(){"loaded"!==this.state&&this.actionQueue.push(this.stop.bind(this)),(this.paused||this.playing)&&(this.playing=!1,this.paused=!1,this.destroySource(),this.resetConfig())}onload(t){this.state="loaded",this.buffer=t,this.duration=this.buffer.duration,this.actionQueue.forEach((t=>t())),this.actionQueue.length=0}onDestroy(){this.actionQueue.length=0,this.destroySource()}resetConfig(){this.config.seek=0}getCurrentTime(){return this.config.loop&&this.duration>0?(this.systemContext.currentTime-this.playTime)%this.duration:this.systemContext.currentTime-this.playTime}createSource(){this.systemContext&&"loaded"===this.state&&(this.sourceNode=this.systemContext.createBufferSource(),this.sourceNode.buffer=this.buffer,this.sourceNode.loop=this.config.loop,this.gainNode||(this.gainNode=this.systemContext.createGain(),this.gainNode.connect(this.systemDestination),_extends(this,this.config)),this.sourceNode.connect(this.gainNode))}destroySource(){this.sourceNode&&(this.sourceNode.removeEventListener("ended",this.endedListener),this.sourceNode.stop(),this.sourceNode.disconnect(),this.sourceNode=null,this.startTime=0,this.playTime=0,this.playing=!1)}}n.componentName="Sound";var r=n;return t.Sound=r,t.SoundSystem=o,Object.defineProperty(t,"__esModule",{value:!0}),t}({},EVA);window.EVA.plugin.sound=window.EVA.plugin.sound||_EVA_IIFE_sound;
|
|
1
|
+
function ownKeys(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),s.push.apply(s,i)}return s}function _objectSpread(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?ownKeys(Object(s),!0).forEach((function(e){_defineProperty(t,e,s[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):ownKeys(Object(s)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))}))}return t}function _defineProperty(t,e,s){return(e=_toPropertyKey(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function _toPropertyKey(t){var e=_toPrimitive(t,"string");return"symbol"==typeof e?e:e+""}function _toPrimitive(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var i=s.call(t,e||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}function _extends(){return _extends=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var i in s)({}).hasOwnProperty.call(s,i)&&(t[i]=s[i])}return t},_extends.apply(null,arguments)}globalThis.EVA=globalThis.EVA||{},globalThis.EVA.plugin=globalThis.EVA.plugin||{};var _EVA_IIFE_sound=function(t,e,s){"use strict";function i(t,e,s,i){return new(s||(s=Promise))((function(o,r){function n(t){try{h(i.next(t))}catch(t){r(t)}}function u(t){try{h(i.throw(t))}catch(t){r(t)}}function h(t){var e;t.done?o(t.value):(e=t.value,e instanceof s?e:new s((function(t){t(e)}))).then(n,u)}h((i=i.apply(t,e||[])).next())}))}let o;function r(){return o}class n{static setParamValue(t,e){if(t.setValueAtTime){const s=r().context;t.setValueAtTime(e,s.audioContext.currentTime)}else t.value=e;return e}}class u extends s.EventEmitter{constructor(){super(...arguments),this.speed=1,this.muted=!1,this.volume=1,this.paused=!1}refresh(){this.emit("refresh")}refreshPaused(){this.emit("refreshPaused")}get filters(){return console.warn("HTML Audio does not support filters"),null}set filters(t){console.warn("HTML Audio does not support filters")}get audioContext(){return console.warn("HTML Audio does not support audioContext"),null}toggleMute(){return this.muted=!this.muted,this.refresh(),this.muted}togglePause(){return this.paused=!this.paused,this.refreshPaused(),this.paused}destroy(){this.removeAllListeners()}}let h=0;const a=class extends s.EventEmitter{constructor(t){super(),this.id=h++,this.init(t)}set(t,e){if(void 0===this[t])throw new Error(`Property with name ${t} does not exist.`);switch(t){case"speed":this.speed=e;break;case"volume":this.volume=e;break;case"paused":this.paused=e;break;case"loop":this.loop=e;break;case"muted":this.muted=e}return this}get progress(){const{currentTime:t}=this._source;return t/this._duration}get paused(){return this._paused}set paused(t){this._paused=t,this.refreshPaused()}_onPlay(){this._playing=!0}_onPause(){this._playing=!1}init(t){this._playing=!1,this._duration=t.source.duration;const e=this._source=t.source.cloneNode(!1);e.src=t.parent.url,e.onplay=this._onPlay.bind(this),e.onpause=this._onPause.bind(this),t.context.on("refresh",this.refresh,this),t.context.on("refreshPaused",this.refreshPaused,this),this._media=t}_internalStop(){this._source&&this._playing&&(this._source.onended=null,this._source.pause())}stop(){this._internalStop(),this._source&&this.emit("stop")}get speed(){return this._speed}set speed(t){this._speed=t,this.refresh()}get volume(){return this._volume}set volume(t){this._volume=t,this.refresh()}get loop(){return this._loop}set loop(t){this._loop=t,this.refresh()}get muted(){return this._muted}set muted(t){this._muted=t,this.refresh()}get filters(){return console.warn("HTML Audio does not support filters"),null}set filters(t){console.warn("HTML Audio does not support filters")}refresh(){const t=this._media.context,e=this._media.parent;this._source.loop=this._loop||e.loop;const s=t.volume*(t.muted?0:1),i=e.volume*(e.muted?0:1),o=this._volume*(this._muted?0:1);this._source.volume=o*s*i,this._source.playbackRate=this._speed*t.speed*e.speed}refreshPaused(){const t=this._media.context,e=this._media.parent,s=this._paused||e.paused||t.paused;s!==this._pausedReal&&(this._pausedReal=s,s?(this._internalStop(),this.emit("paused")):(this.emit("resumed"),this.play({start:this._source.currentTime,end:this._end,volume:this._volume,speed:this._speed,loop:this._loop})),this.emit("pause",s))}play(t){const{start:e,end:i,speed:o,loop:r,volume:n,muted:u}=t;i&&console.assert(i>e,"End time is before start time"),this._speed=o,this._volume=n,this._loop=!!r,this._muted=u,this.refresh(),this.loop&&null!==i&&(console.warn('Looping not support when specifying an "end" time'),this.loop=!1),this._start=e,this._end=i||this._duration,this._start=Math.max(0,this._start-a.PADDING),this._end=Math.min(this._end+a.PADDING,this._duration),this._source.onloadedmetadata=()=>{this._source&&(this._source.currentTime=e,this._source.onloadedmetadata=null,this.emit("progress",e/this._duration,this._duration),s.Ticker.shared.add(this._onUpdate,this))},this._source.onended=this._onComplete.bind(this),this._source.play(),this.emit("start")}_onUpdate(){this.emit("progress",this.progress,this._duration),this._source.currentTime>=this._end&&!this._source.loop&&this._onComplete()}_onComplete(){s.Ticker.shared.remove(this._onUpdate,this),this._internalStop(),this.emit("progress",1,this._duration),this.emit("end",this)}destroy(){s.Ticker.shared.remove(this._onUpdate,this),this.removeAllListeners();const t=this._source;t&&(t.onended=null,t.onplay=null,t.onpause=null,this._internalStop()),this._source=null,this._speed=1,this._volume=1,this._loop=!1,this._end=null,this._start=0,this._duration=0,this._playing=!1,this._pausedReal=!1,this._paused=!1,this._muted=!1,this._media&&(this._media.context.off("refresh",this.refresh,this),this._media.context.off("refreshPaused",this.refreshPaused,this),this._media=null)}toString(){return`[HTMLAudioInstance id=${this.id}]`}};let l=a;l.PADDING=.1;class d extends s.EventEmitter{init(t){this.parent=t,this._source=t.options.source||new Audio,t.url&&(this._source.src=t.url)}create(){return new l(this)}get isPlayable(){return!!this._source&&4===this._source.readyState}get duration(){return this._source.duration}get context(){return this.parent.context}get filters(){return null}set filters(t){console.warn("HTML Audio does not support filters")}destroy(){this.removeAllListeners(),this.parent=null,this._source&&(this._source.src="",this._source.load(),this._source=null)}get source(){return this._source}load(t){const e=this._source,s=this.parent;if(4===e.readyState){s.isLoaded=!0;const e=s.autoPlayStart();return void(t&&setTimeout((()=>{t(null,s,e)}),0))}if(!s.url)return void t(new Error("sound.url or sound.source must be set"));e.src=s.url;const i=()=>{n(),s.isLoaded=!0;const e=s.autoPlayStart();t&&t(null,s,e)},o=()=>{n(),t&&t(new Error("Sound loading has been aborted"))},r=()=>{n();const s=`Failed to load audio element (code: ${e.error.code})`;t?t(new Error(s)):console.error(s)},n=()=>{e.removeEventListener("canplaythrough",i),e.removeEventListener("load",i),e.removeEventListener("abort",o),e.removeEventListener("error",r)};e.addEventListener("canplaythrough",i,!1),e.addEventListener("load",i,!1),e.addEventListener("abort",o,!1),e.addEventListener("error",r,!1),e.load()}}class c{constructor(t,e){this.parent=t,_extends(this,e),this.duration=this.end-this.start,console.assert(this.duration>0,"End time must be after start time")}play(t){return this.parent.play({complete:t,speed:this.speed||this.parent.speed,end:this.end,start:this.start,loop:this.loop})}destroy(){this.parent=null}}const p=["ogg","oga","opus","m4a","mp3","mpeg","wav","aiff","wma","mid","caf"],_=["audio/mpeg","audio/ogg"],f={};function m(t){const e=_objectSpread({m4a:"audio/mp4",oga:"audio/ogg",opus:'audio/ogg; codecs="opus"',caf:'audio/x-caf; codecs="opus"'},t||{}),s=document.createElement("audio"),i={},o=/^no$/;p.forEach((t=>{const r=s.canPlayType(`audio/${t}`).replace(o,""),n=e[t]?s.canPlayType(e[t]).replace(o,""):"";i[t]=!!r||!!n})),_extends(f,i)}m();let g=0;class y extends s.EventEmitter{constructor(t){super(),this.id=g++,this._media=null,this._paused=!1,this._muted=!1,this._elapsed=0,this.init(t)}set(t,e){if(void 0===this[t])throw new Error(`Property with name ${t} does not exist.`);switch(t){case"speed":this.speed=e;break;case"volume":this.volume=e;break;case"muted":this.muted=e;break;case"loop":this.loop=e;break;case"paused":this.paused=e}return this}stop(){this._source&&(this._internalStop(),this.emit("stop"))}get speed(){return this._speed}set speed(t){this._speed=t,this.refresh(),this._update(!0)}get volume(){return this._volume}set volume(t){this._volume=t,this.refresh()}get muted(){return this._muted}set muted(t){this._muted=t,this.refresh()}get loop(){return this._loop}set loop(t){this._loop=t,this.refresh()}get filters(){return this._filters}set filters(t){var e;this._filters&&(null===(e=this._filters)||void 0===e||e.filter((t=>t)).forEach((t=>t.disconnect())),this._filters=null,this._source.connect(this._gain));this._filters=null!=t&&t.length?t.slice(0):null,this.refresh()}refresh(){if(!this._source)return;const t=this._media.context,e=this._media.parent;this._source.loop=this._loop||e.loop;const s=t.volume*(t.muted?0:1),i=e.volume*(e.muted?0:1),o=this._volume*(this._muted?0:1);n.setParamValue(this._gain.gain,o*i*s),n.setParamValue(this._source.playbackRate,this._speed*e.speed*t.speed),this.applyFilters()}applyFilters(){var t;if(null!==(t=this._filters)&&void 0!==t&&t.length){this._source.disconnect();let t=this._source;this._filters.forEach((e=>{t.connect(e.destination),t=e})),t.connect(this._gain)}}refreshPaused(){const t=this._media.context,e=this._media.parent,s=this._paused||e.paused||t.paused;s!==this._pausedReal&&(this._pausedReal=s,s?(this._internalStop(),this.emit("paused")):(this.emit("resumed"),this.play({start:this._elapsed%this._duration,end:this._end,speed:this._speed,loop:this._loop,volume:this._volume})),this.emit("pause",s))}play(t){const{start:e,end:s,speed:i,loop:o,volume:r,muted:n,filters:u}=t;s&&console.assert(s>e,"End time is before start time"),this._paused=!1;const{source:h,gain:a}=this._media.nodes.cloneBufferSource();this._source=h,this._gain=a,this._speed=i,this._volume=r,this._loop=!!o,this._muted=n,this._filters=u,this.refresh();const l=this._source.buffer.duration;this._duration=l,this._end=s,this._lastUpdate=this._now(),this._elapsed=e,this._source.onended=this._onComplete.bind(this),this._loop?(this._source.loopEnd=s,this._source.loopStart=e,this._source.start(0,e)):s?this._source.start(0,e,s-e):this._source.start(0,e),this.emit("start"),this._update(!0),this.enableTicker(!0)}enableTicker(t){s.Ticker.shared.remove(this._updateListener,this),t&&s.Ticker.shared.add(this._updateListener,this)}get progress(){return this._progress}get paused(){return this._paused}set paused(t){this._paused=t,this.refreshPaused()}destroy(){var t;this.removeAllListeners(),this._internalStop(),this._gain&&(this._gain.disconnect(),this._gain=null),this._media&&(this._media.context.events.off("refresh",this.refresh,this),this._media.context.events.off("refreshPaused",this.refreshPaused,this),this._media=null),null===(t=this._filters)||void 0===t||t.forEach((t=>t.disconnect())),this._filters=null,this._end=null,this._speed=1,this._volume=1,this._loop=!1,this._elapsed=0,this._duration=0,this._paused=!1,this._muted=!1,this._pausedReal=!1}toString(){return`[WebAudioInstance id=${this.id}]`}_now(){return this._media.context.audioContext.currentTime}_updateListener(){this._update()}_update(t=!1){if(this._source){const e=this._now(),s=e-this._lastUpdate;if(s>0||t){const t=this._source.playbackRate.value;this._elapsed+=s*t,this._lastUpdate=e;const i=this._duration;let o;if(this._source.loopStart){const t=this._source.loopEnd-this._source.loopStart;o=(this._source.loopStart+this._elapsed%t)/i}else o=this._elapsed%i/i;this._progress=o,this.emit("progress",this._progress,i)}}}init(t){this._media=t,t.context.events.on("refresh",this.refresh,this),t.context.events.on("refreshPaused",this.refreshPaused,this)}_internalStop(){if(this._source){this.enableTicker(!1),this._source.onended=null,this._source.stop(0),this._source.disconnect();try{this._source.buffer=null}catch(t){console.warn("Failed to set AudioBufferSourceNode.buffer to null:",t)}this._source=null}}_onComplete(){if(this._source){this.enableTicker(!1),this._source.onended=null,this._source.disconnect();try{this._source.buffer=null}catch(t){console.warn("Failed to set AudioBufferSourceNode.buffer to null:",t)}}this._source=null,this._progress=1,this.emit("progress",1,this._duration),this.emit("end",this)}}class v{constructor(t,e){this._output=e,this._input=t}get destination(){return this._input}get filters(){return this._filters}set filters(t){if(this._filters&&(this._filters.forEach((t=>{t&&t.disconnect()})),this._filters=null,this._input.connect(this._output)),t&&t.length){this._filters=t.slice(0),this._input.disconnect();let e=null;t.forEach((t=>{null===e?this._input.connect(t.destination):e.connect(t.destination),e=t})),e.connect(this._output)}}destroy(){this.filters=null,this._input=null,this._output=null}}const b=class extends v{constructor(t){const e=t.audioContext,s=e.createBufferSource(),i=e.createGain(),o=e.createAnalyser();s.connect(o),o.connect(i),i.connect(t.destination),super(o,i),this.context=t,this.bufferSource=s,this.gain=i,this.analyser=o}get script(){return this._script||(this._script=this.context.audioContext.createScriptProcessor(b.BUFFER_SIZE),this._script.connect(this.context.destination)),this._script}destroy(){super.destroy(),this.bufferSource.disconnect(),this._script&&this._script.disconnect(),this.gain.disconnect(),this.analyser.disconnect(),this.bufferSource=null,this._script=null,this.gain=null,this.analyser=null,this.context=null}cloneBufferSource(){const t=this.bufferSource,e=this.context.audioContext.createBufferSource();e.buffer=t.buffer,n.setParamValue(e.playbackRate,t.playbackRate.value),e.loop=t.loop;const s=this.context.audioContext.createGain();return e.connect(s),s.connect(this.destination),{source:e,gain:s}}get bufferSize(){return this.script.bufferSize}};let x=b;x.BUFFER_SIZE=0;class P{init(t){this.parent=t,this._nodes=new x(this.context),this._source=this._nodes.bufferSource,this.source=t.options.source}destroy(){this.parent=null,this._nodes.destroy(),this._nodes=null;try{this._source.buffer=null}catch(t){console.warn("Failed to set AudioBufferSourceNode.buffer to null:",t)}this._source=null,this.source=null}create(){return new y(this)}get context(){return this.parent.context}get isPlayable(){return!!this._source&&!!this._source.buffer}get filters(){return this._nodes.filters}set filters(t){this._nodes.filters=t}get duration(){return console.assert(this.isPlayable,"Sound not yet playable, no duration"),this._source.buffer.duration}get buffer(){return this._source.buffer}set buffer(t){this._source.buffer=t}get nodes(){return this._nodes}load(t){this.source?this._decode(this.source,t):this.parent.url?this._loadUrl(t):t?t(new Error("sound.url or sound.source must be set")):console.error("sound.url or sound.source must be set")}async _loadUrl(t){const e=this.parent.url,i=await s.DOMAdapter.get().fetch(e);this._decode(await i.arrayBuffer(),t)}_decode(t,e){const s=(t,s)=>{if(t)e&&e(t);else{this.parent.isLoaded=!0,this.buffer=s;const t=this.parent.autoPlayStart();e&&e(null,this.parent,t)}};if(t instanceof AudioBuffer)s(null,t);else{this.parent.context.decode(t,s)}}}const A=class{static from(t){let e={};"string"==typeof t?e.url=t:t instanceof ArrayBuffer||t instanceof AudioBuffer||t instanceof HTMLAudioElement?e.source=t:Array.isArray(t)?e.url=t:e=t,e=_objectSpread({autoPlay:!1,singleInstance:!1,url:null,source:null,preload:!1,volume:1,speed:1,complete:null,loaded:null,loop:!1},e),Object.freeze(e);const s=r().useLegacy?new d:new P;return new A(s,e)}constructor(t,e){this.media=t,this.options=e,this._instances=[],this._sprites={},this.media.init(this);const s=e.complete;this._autoPlayOptions=s?{complete:s}:null,this.isLoaded=!1,this._preloadQueue=null,this.isPlaying=!1,this.autoPlay=e.autoPlay,this.singleInstance=e.singleInstance,this.preload=e.preload||this.autoPlay,this.url=Array.isArray(e.url)?this.preferUrl(e.url):e.url,this.speed=e.speed,this.volume=e.volume,this.loop=e.loop,e.sprites&&this.addSprites(e.sprites),this.preload&&this._preload(e.loaded)}preferUrl(t){const[e]=t.map((t=>({url:t,ext:s.path.extname(t).slice(1)}))).filter((({ext:t})=>f[t])).sort(((t,e)=>p.indexOf(t.ext)-p.indexOf(e.ext)));if(!e)throw new Error("No supported file type found");return e.url}get context(){return r().context}pause(){return this.isPlaying=!1,this.paused=!0,this}resume(){return this.isPlaying=this._instances.length>0,this.paused=!1,this}get paused(){return this._paused}set paused(t){this._paused=t,this.refreshPaused()}get speed(){return this._speed}set speed(t){this._speed=t,this.refresh()}get filters(){return this.media.filters}set filters(t){this.media.filters=t}addSprites(t,e){if("object"==typeof t){const e={};for(const s in t)e[s]=this.addSprites(s,t[s]);return e}console.assert(!this._sprites[t],`Alias ${t} is already taken`);const s=new c(this,e);return this._sprites[t]=s,s}destroy(){this._removeInstances(),this.removeSprites(),this.media.destroy(),this.media=null,this._sprites=null,this._instances=null}removeSprites(t){if(t){const e=this._sprites[t];void 0!==e&&(e.destroy(),delete this._sprites[t])}else for(const t in this._sprites)this.removeSprites(t);return this}get isPlayable(){return this.isLoaded&&this.media&&this.media.isPlayable}stop(){if(!this.isPlayable)return this.autoPlay=!1,this._autoPlayOptions=null,this;this.isPlaying=!1;for(let t=this._instances.length-1;t>=0;t--)this._instances[t].stop();return this}play(t,e){let s;if("string"==typeof t){s={sprite:t,loop:this.loop,complete:e}}else"function"==typeof t?(s={},s.complete=t):s=t;if(s=_objectSpread({complete:null,loaded:null,sprite:null,end:null,start:0,volume:1,speed:1,muted:!1,loop:!1},s||{}),s.sprite){const t=s.sprite;console.assert(!!this._sprites[t],`Alias ${t} is not available`);const e=this._sprites[t];s.start=e.start+(s.start||0),s.end=e.end,s.speed=e.speed||1,s.loop=e.loop||s.loop,delete s.sprite}if(s.offset&&(s.start=s.offset),!this.isLoaded)return this._preloadQueue?new Promise((t=>{this._preloadQueue.push((()=>{t(this.play(s))}))})):(this._preloadQueue=[],this.autoPlay=!0,this._autoPlayOptions=s,new Promise(((t,e)=>{this._preload(((i,o,r)=>{this._preloadQueue.forEach((t=>t())),this._preloadQueue=null,i?e(i):(s.loaded&&s.loaded(i,o,r),t(r))}))})));(this.singleInstance||s.singleInstance)&&this._removeInstances();const i=this._createInstance();return this._instances.push(i),this.isPlaying=!0,i.once("end",(()=>{s.complete&&s.complete(this),this._onComplete(i)})),i.once("stop",(()=>{this._onComplete(i)})),i.play(s),i}refresh(){const t=this._instances.length;for(let e=0;e<t;e++)this._instances[e].refresh()}refreshPaused(){const t=this._instances.length;for(let e=0;e<t;e++)this._instances[e].refreshPaused()}get volume(){return this._volume}set volume(t){this._volume=t,this.refresh()}get muted(){return this._muted}set muted(t){this._muted=t,this.refresh()}get loop(){return this._loop}set loop(t){this._loop=t,this.refresh()}_preload(t){this.media.load(t)}get instances(){return this._instances}get sprites(){return this._sprites}get duration(){return this.media.duration}autoPlayStart(){let t;return this.autoPlay&&(t=this.play(this._autoPlayOptions)),t}_removeInstances(){for(let t=this._instances.length-1;t>=0;t--)this._poolInstance(this._instances[t]);this._instances.length=0}_onComplete(t){if(this._instances){const e=this._instances.indexOf(t);e>-1&&this._instances.splice(e,1),this.isPlaying=this._instances.length>0}this._poolInstance(t)}_createInstance(){if(A._pool.length>0){const t=A._pool.pop();return t.init(this.media),t}return this.media.create()}_poolInstance(t){t.destroy(),A._pool.indexOf(t)<0&&A._pool.push(t)}};let w=A;w._pool=[];class E extends v{constructor(){const t=window,e=new E.AudioContext,i=e.createDynamicsCompressor(),o=e.createAnalyser();o.connect(i),i.connect(e.destination),super(o,i),this.autoPause=!0,this._ctx=e,this._offlineCtx=new E.OfflineAudioContext(1,2,t.OfflineAudioContext?Math.max(8e3,Math.min(96e3,e.sampleRate)):44100),this.compressor=i,this.analyser=o,this.events=new s.EventEmitter,this.volume=1,this.speed=1,this.muted=!1,this.paused=!1,this._locked="suspended"===e.state&&("ontouchstart"in globalThis||"onclick"in globalThis),this._locked&&(this._unlock(),this._unlock=this._unlock.bind(this),document.addEventListener("mousedown",this._unlock,!0),document.addEventListener("touchstart",this._unlock,!0),document.addEventListener("touchend",this._unlock,!0)),this.onFocus=this.onFocus.bind(this),this.onBlur=this.onBlur.bind(this),globalThis.addEventListener("focus",this.onFocus),globalThis.addEventListener("blur",this.onBlur)}onFocus(){if(!this.autoPause)return;const t=this._ctx.state;"suspended"!==t&&"interrupted"!==t&&this._locked||(this.paused=this._pausedOnBlur,this.refreshPaused())}onBlur(){this.autoPause&&(this._locked||(this._pausedOnBlur=this._paused,this.paused=!0,this.refreshPaused()))}_unlock(){this._locked&&(this.playEmptySound(),"running"===this._ctx.state&&(document.removeEventListener("mousedown",this._unlock,!0),document.removeEventListener("touchend",this._unlock,!0),document.removeEventListener("touchstart",this._unlock,!0),this._locked=!1))}playEmptySound(){const t=this._ctx.createBufferSource();if(t.buffer=this._ctx.createBuffer(1,1,22050),t.connect(this._ctx.destination),t.start(0,0,0),"suspended"===t.context.state){const e=t.context.resume();e.catch&&e.catch((()=>{}))}}static get AudioContext(){const t=window;return t.AudioContext||t.webkitAudioContext||null}static get OfflineAudioContext(){const t=window;return t.OfflineAudioContext||t.webkitOfflineAudioContext||null}destroy(){super.destroy();const t=this._ctx;void 0!==t.close&&t.close(),globalThis.removeEventListener("focus",this.onFocus),globalThis.removeEventListener("blur",this.onBlur),this.events.removeAllListeners(),this.analyser.disconnect(),this.compressor.disconnect(),this.analyser=null,this.compressor=null,this.events=null,this._offlineCtx=null,this._ctx=null}get audioContext(){return this._ctx}get offlineContext(){return this._offlineCtx}set paused(t){t&&"running"===this._ctx.state?this._ctx.suspend().catch((()=>{})):t||"suspended"!==this._ctx.state||this._ctx.resume().catch((()=>{})),this._paused=t}get paused(){return this._paused}refresh(){this.events.emit("refresh")}refreshPaused(){this.events.emit("refreshPaused")}toggleMute(){return this.muted=!this.muted,this.refresh(),this.muted}togglePause(){return this.paused=!this.paused,this.refreshPaused(),this._paused}decode(t,e){const s=t=>{e(new Error((null==t?void 0:t.message)||"Unable to decode file"))},i=this._offlineCtx.decodeAudioData(t,(t=>{e(null,t)}),s);i&&i.catch(s)}}const S=t=>{var e;const i=t.src;let o=null==t||null===(e=t.alias)||void 0===e?void 0:e[0];return o&&t.src!==o||(o=s.path.basename(i,s.path.extname(i))),o},C={extension:s.ExtensionType.Asset,detection:{test:async()=>!0,add:async t=>[...t,...p.filter((t=>f[t]))],remove:async t=>t.filter((e=>t.includes(e)))},loader:{name:"sound",extension:{type:[s.ExtensionType.LoadParser],priority:s.LoaderParserPriority.High},test(t){const e=s.path.extname(t).slice(1);return!!f[e]||_.some((e=>t.startsWith(`data:${e}`)))},async load(t,e){const s=await new Promise(((s,i)=>w.from(_objectSpread(_objectSpread({},e.data),{},{url:t,preload:!0,loaded(t,o){var r,n;t?i(t):s(o),null===(r=e.data)||void 0===r||null===(n=r.loaded)||void 0===n||n.call(r,t,o)}}))));return r().add(S(e),s),s},async unload(t,e){r().remove(S(e))}}};s.extensions.add(C);const L=function(t){return o=t,t}(new class{constructor(){this.init()}init(){return this.supported&&(this._webAudioContext=new E),this._htmlAudioContext=new u,this._sounds={},this.useLegacy=!this.supported,this}get context(){return this._context}get filtersAll(){return this.useLegacy?[]:this._context.filters}set filtersAll(t){this.useLegacy||(this._context.filters=t)}get supported(){return null!==E.AudioContext}add(t,e){if("object"==typeof t){const s={};for(const i in t){const o=this._getOptions(t[i],e);s[i]=this.add(i,o)}return s}if(console.assert(!this._sounds[t],`Sound with alias ${t} already exists.`),e instanceof w)return this._sounds[t]=e,e;const s=this._getOptions(e),i=w.from(s);return this._sounds[t]=i,i}_getOptions(t,e){let s;return s="string"==typeof t||Array.isArray(t)?{url:t}:t instanceof ArrayBuffer||t instanceof AudioBuffer||t instanceof HTMLAudioElement?{source:t}:t,s=_objectSpread(_objectSpread({},s),e||{}),s}get useLegacy(){return this._useLegacy}set useLegacy(t){this._useLegacy=t,this._context=!t&&this.supported?this._webAudioContext:this._htmlAudioContext}get disableAutoPause(){return this._webAudioContext?!this._webAudioContext.autoPause:(console.warn("WebAudioContext is not initialized."),!1)}set disableAutoPause(t){this._webAudioContext?this._webAudioContext.autoPause=!t:console.warn("WebAudioContext is not initialized.")}remove(t){return this.exists(t,!0),this._sounds[t].destroy(),delete this._sounds[t],this}get volumeAll(){return this._context.volume}set volumeAll(t){this._context.volume=t,this._context.refresh()}get speedAll(){return this._context.speed}set speedAll(t){this._context.speed=t,this._context.refresh()}togglePauseAll(){return this._context.togglePause()}pauseAll(){return this._context.paused=!0,this._context.refreshPaused(),this}resumeAll(){return this._context.paused=!1,this._context.refreshPaused(),this}toggleMuteAll(){return this._context.toggleMute()}muteAll(){return this._context.muted=!0,this._context.refresh(),this}unmuteAll(){return this._context.muted=!1,this._context.refresh(),this}removeAll(){for(const t in this._sounds)this._sounds[t].destroy(),delete this._sounds[t];return this}stopAll(){for(const t in this._sounds)this._sounds[t].stop();return this}exists(t,e=!1){const s=!!this._sounds[t];return e&&console.assert(s,`No sound matching alias '${t}'.`),s}isPlaying(){for(const t in this._sounds)if(this._sounds[t].isPlaying)return!0;return!1}find(t){return this.exists(t,!0),this._sounds[t]}play(t,e){return this.find(t).play(e)}stop(t){return this.find(t).stop()}pause(t){return this.find(t).pause()}resume(t){return this.find(t).resume()}volume(t,e){const s=this.find(t);return void 0!==e&&(s.volume=e),s.volume}speed(t,e){const s=this.find(t);return void 0!==e&&(s.speed=e),s.speed}duration(t){return this.find(t).duration}close(){return this.removeAll(),this._sounds=null,this._webAudioContext&&(this._webAudioContext.destroy(),this._webAudioContext=null),this._htmlAudioContext&&(this._htmlAudioContext.destroy(),this._htmlAudioContext=null),this._context=null,this}});L.disableAutoPause=!0,p.push("aac"),m({aac:"audio/aac"}),s.extensions.add(C);let T=class extends e.System{constructor(t){super(),this.autoPauseAndStart=!0,this.components=[],this.audioBufferCache={},_extends(this,t),(null==t?void 0:t.useLegacy)&&(L.useLegacy=!0)}resumeAll(){L.resumeAll()}pauseAll(){L.pauseAll()}stopAll(){L.stopAll()}update(){const t=this.componentObserver.clear();for(const e of t)this.componentChanged(e)}onResume(){this.autoPauseAndStart&&this.resumeAll()}onPause(){this.autoPauseAndStart&&this.pauseAll()}onDestroy(){this.components.forEach((t=>{t.onDestroy()})),this.components=[],L.removeAll()}componentChanged(t){return i(this,void 0,void 0,(function*(){"Sound"===t.componentName&&t.type===e.OBSERVER_TYPE.ADD&&this.add(t)}))}add(t){var s,o;return i(this,void 0,void 0,(function*(){const i=t.component;this.components.push(i);try{const{config:t}=i;i.state="loading";const r=yield e.resource.getResource(t.resource);!this.audioBufferCache[r.name]&&(null===(s=null==r?void 0:r.data)||void 0===s?void 0:s.audio)&&(this.audioBufferCache[r.name]=null===(o=null==r?void 0:r.data)||void 0===o?void 0:o.audio),this.audioBufferCache[r.name]&&i.onload(this.audioBufferCache[r.name])}catch(t){this.onError&&this.onError(t)}}))}};T.systemName="SoundSystem",T=function(t,e,s,i){var o,r=arguments.length,n=r<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,s):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,s,i);else for(var u=t.length-1;u>=0;u--)(o=t[u])&&(n=(r<3?o(n):r>3?o(e,s,n):o(e,s))||n);return r>3&&n&&Object.defineProperty(e,s,n),n}([e.decorators.componentObserver({Sound:[]})],T);var O=T;class k extends e.Component{constructor(){super(...arguments),this.state="unloaded",this.config={resource:"",autoplay:!1,muted:!1,volume:1,loop:!1,seek:0,speed:1},this.actionQueue=[],this.startTime=0}get systemContext(){return L.context.audioContext}get playing(){return!!this.buffer&&this.buffer.isPlaying}get muted(){var t;return(null===(t=this.buffer)||void 0===t?void 0:t.muted)||!1}set muted(t){this.buffer&&(this.buffer.muted=t)}get volume(){var t;return(null===(t=this.buffer)||void 0===t?void 0:t.volume)||0}set volume(t){this.buffer&&(this.buffer.volume=t)}init(t){t&&(_extends(this.config,t),this.config.autoplay&&this.actionQueue.push(this.play.bind(this)))}play(){"loaded"!==this.state&&this.actionQueue.push(this.play.bind(this)),this.buffer&&(this.startTime=this.systemContext.currentTime,this.buffer.play())}resume(){this.buffer&&this.buffer.resume()}pause(){this.buffer&&this.buffer.pause()}stop(){this.buffer&&this.buffer.stop()}onload(t){this.state="loaded",this.buffer=t,this.buffer.muted=this.config.muted,this.buffer.volume=this.config.volume,this.buffer.loop=this.config.loop,this.buffer.speed=this.config.speed,this.actionQueue.forEach((t=>t())),this.actionQueue.length=0}onDestroy(){this.actionQueue.length=0,this.startTime=0,this.buffer&&(this.buffer.destroy(),this.buffer=null)}}k.componentName="Sound";var j=k;return t.Sound=j,t.SoundSystem=O,Object.defineProperty(t,"__esModule",{value:!0}),t}({},EVA,PIXI);globalThis.EVA.plugin.sound=globalThis.EVA.plugin.sound||_EVA_IIFE_sound;
|
package/dist/plugin-sound.cjs.js
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
5
|
var eva_js = require('@eva/eva.js');
|
|
6
|
+
var pixiSound = require('@ali/pixi-sound');
|
|
7
|
+
var pixi_js = require('pixi.js');
|
|
6
8
|
|
|
7
9
|
/*! *****************************************************************************
|
|
8
10
|
Copyright (c) Microsoft Corporation. All rights reserved.
|
|
@@ -35,69 +37,31 @@ function __awaiter(thisArg, _arguments, P, generator) {
|
|
|
35
37
|
});
|
|
36
38
|
}
|
|
37
39
|
|
|
40
|
+
pixiSound.sound.disableAutoPause = true;
|
|
41
|
+
pixiSound.utils.extensions.push('aac');
|
|
42
|
+
pixiSound.utils.validateFormats({
|
|
43
|
+
aac: 'audio/aac',
|
|
44
|
+
});
|
|
45
|
+
pixi_js.extensions.add(pixiSound.soundAsset);
|
|
38
46
|
let SoundSystem = class SoundSystem extends eva_js.System {
|
|
39
47
|
constructor(obj) {
|
|
40
48
|
super();
|
|
41
49
|
this.autoPauseAndStart = true;
|
|
42
50
|
this.components = [];
|
|
43
|
-
this.pausedComponents = [];
|
|
44
51
|
this.audioBufferCache = {};
|
|
45
|
-
this.decodeAudioPromiseMap = {};
|
|
46
52
|
Object.assign(this, obj);
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
return this.gainNode ? this.gainNode.gain.value === 0 : false;
|
|
50
|
-
}
|
|
51
|
-
set muted(v) {
|
|
52
|
-
if (!this.gainNode) {
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
55
|
-
this.gainNode.gain.setValueAtTime(v ? 0 : 1, 0);
|
|
56
|
-
}
|
|
57
|
-
get volume() {
|
|
58
|
-
return this.gainNode ? this.gainNode.gain.value : 1;
|
|
59
|
-
}
|
|
60
|
-
set volume(v) {
|
|
61
|
-
if (!this.gainNode || typeof v !== 'number' || v < 0 || v > 1) {
|
|
62
|
-
return;
|
|
63
|
-
}
|
|
64
|
-
this.gainNode.gain.setValueAtTime(v, 0);
|
|
65
|
-
}
|
|
66
|
-
get audioLocked() {
|
|
67
|
-
if (!this.ctx) {
|
|
68
|
-
return true;
|
|
53
|
+
if (obj === null || obj === void 0 ? void 0 : obj.useLegacy) {
|
|
54
|
+
pixiSound.sound.useLegacy = true;
|
|
69
55
|
}
|
|
70
|
-
return this.ctx.state !== 'running';
|
|
71
56
|
}
|
|
72
57
|
resumeAll() {
|
|
73
|
-
|
|
74
|
-
this.pausedComponents.forEach(component => {
|
|
75
|
-
component.play();
|
|
76
|
-
});
|
|
77
|
-
this.pausedComponents = [];
|
|
78
|
-
};
|
|
79
|
-
this.ctx.resume().then(handleResume, handleResume);
|
|
58
|
+
pixiSound.sound.resumeAll();
|
|
80
59
|
}
|
|
81
60
|
pauseAll() {
|
|
82
|
-
|
|
83
|
-
if (component.playing) {
|
|
84
|
-
this.pausedComponents.push(component);
|
|
85
|
-
component.pause();
|
|
86
|
-
}
|
|
87
|
-
});
|
|
88
|
-
this.ctx.suspend().then();
|
|
61
|
+
pixiSound.sound.pauseAll();
|
|
89
62
|
}
|
|
90
63
|
stopAll() {
|
|
91
|
-
|
|
92
|
-
if (component.playing) {
|
|
93
|
-
component.stop();
|
|
94
|
-
}
|
|
95
|
-
});
|
|
96
|
-
this.pausedComponents = [];
|
|
97
|
-
this.ctx.suspend().then();
|
|
98
|
-
}
|
|
99
|
-
init() {
|
|
100
|
-
this.setupAudioContext();
|
|
64
|
+
pixiSound.sound.stopAll();
|
|
101
65
|
}
|
|
102
66
|
update() {
|
|
103
67
|
const changes = this.componentObserver.clear();
|
|
@@ -122,12 +86,7 @@ let SoundSystem = class SoundSystem extends eva_js.System {
|
|
|
122
86
|
component.onDestroy();
|
|
123
87
|
});
|
|
124
88
|
this.components = [];
|
|
125
|
-
|
|
126
|
-
this.gainNode.disconnect();
|
|
127
|
-
this.gainNode = null;
|
|
128
|
-
this.ctx.close();
|
|
129
|
-
this.ctx = null;
|
|
130
|
-
}
|
|
89
|
+
pixiSound.sound.removeAll();
|
|
131
90
|
}
|
|
132
91
|
componentChanged(changed) {
|
|
133
92
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -138,46 +97,8 @@ let SoundSystem = class SoundSystem extends eva_js.System {
|
|
|
138
97
|
}
|
|
139
98
|
});
|
|
140
99
|
}
|
|
141
|
-
setupAudioContext() {
|
|
142
|
-
try {
|
|
143
|
-
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
|
144
|
-
this.ctx = new AudioContext();
|
|
145
|
-
}
|
|
146
|
-
catch (error) {
|
|
147
|
-
console.error(error);
|
|
148
|
-
if (this.onError) {
|
|
149
|
-
this.onError(error);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
if (!this.ctx) {
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
this.gainNode =
|
|
156
|
-
typeof this.ctx.createGain === 'undefined' ? this.ctx.createGainNode() : this.ctx.createGain();
|
|
157
|
-
this.gainNode.gain.setValueAtTime(this.muted ? 0 : this.volume, this.ctx.currentTime);
|
|
158
|
-
this.gainNode.connect(this.ctx.destination);
|
|
159
|
-
this.unlockAudio();
|
|
160
|
-
}
|
|
161
|
-
unlockAudio() {
|
|
162
|
-
if (!this.ctx || !this.audioLocked) {
|
|
163
|
-
return;
|
|
164
|
-
}
|
|
165
|
-
const unlock = () => {
|
|
166
|
-
if (this.ctx) {
|
|
167
|
-
const removeListenerFn = () => {
|
|
168
|
-
document.body.removeEventListener('touchstart', unlock);
|
|
169
|
-
document.body.removeEventListener('touchend', unlock);
|
|
170
|
-
document.body.removeEventListener('click', unlock);
|
|
171
|
-
};
|
|
172
|
-
this.ctx.resume().then(removeListenerFn, removeListenerFn);
|
|
173
|
-
}
|
|
174
|
-
};
|
|
175
|
-
document.body.addEventListener('touchstart', unlock);
|
|
176
|
-
document.body.addEventListener('touchend', unlock);
|
|
177
|
-
document.body.addEventListener('click', unlock);
|
|
178
|
-
}
|
|
179
100
|
add(changed) {
|
|
180
|
-
var _a;
|
|
101
|
+
var _a, _b;
|
|
181
102
|
return __awaiter(this, void 0, void 0, function* () {
|
|
182
103
|
const component = changed.component;
|
|
183
104
|
this.components.push(component);
|
|
@@ -186,11 +107,9 @@ let SoundSystem = class SoundSystem extends eva_js.System {
|
|
|
186
107
|
component.state = 'loading';
|
|
187
108
|
const audio = yield eva_js.resource.getResource(config.resource);
|
|
188
109
|
if (!this.audioBufferCache[audio.name] && ((_a = audio === null || audio === void 0 ? void 0 : audio.data) === null || _a === void 0 ? void 0 : _a.audio)) {
|
|
189
|
-
this.audioBufferCache[audio.name] =
|
|
110
|
+
this.audioBufferCache[audio.name] = (_b = audio === null || audio === void 0 ? void 0 : audio.data) === null || _b === void 0 ? void 0 : _b.audio;
|
|
190
111
|
}
|
|
191
112
|
if (this.audioBufferCache[audio.name]) {
|
|
192
|
-
component.systemContext = this.ctx;
|
|
193
|
-
component.systemDestination = this.gainNode;
|
|
194
113
|
component.onload(this.audioBufferCache[audio.name]);
|
|
195
114
|
}
|
|
196
115
|
}
|
|
@@ -201,41 +120,6 @@ let SoundSystem = class SoundSystem extends eva_js.System {
|
|
|
201
120
|
}
|
|
202
121
|
});
|
|
203
122
|
}
|
|
204
|
-
decodeAudioData(arraybuffer, name) {
|
|
205
|
-
if (this.decodeAudioPromiseMap[name]) {
|
|
206
|
-
return this.decodeAudioPromiseMap[name];
|
|
207
|
-
}
|
|
208
|
-
const promise = new Promise((resolve, reject) => {
|
|
209
|
-
if (!this.ctx) {
|
|
210
|
-
reject(new Error('No audio support'));
|
|
211
|
-
}
|
|
212
|
-
const success = (decodedData) => {
|
|
213
|
-
if (this.decodeAudioPromiseMap[name]) {
|
|
214
|
-
delete this.decodeAudioPromiseMap[name];
|
|
215
|
-
}
|
|
216
|
-
if (decodedData) {
|
|
217
|
-
resolve(decodedData);
|
|
218
|
-
}
|
|
219
|
-
else {
|
|
220
|
-
reject(new Error(`Error decoding audio ${name}`));
|
|
221
|
-
}
|
|
222
|
-
};
|
|
223
|
-
const error = (err) => {
|
|
224
|
-
if (this.decodeAudioPromiseMap[name]) {
|
|
225
|
-
delete this.decodeAudioPromiseMap[name];
|
|
226
|
-
}
|
|
227
|
-
reject(new Error(`${err}. arrayBuffer byteLength: ${arraybuffer ? arraybuffer.byteLength : 0}`));
|
|
228
|
-
};
|
|
229
|
-
const promise = this.ctx.decodeAudioData(arraybuffer, success, error);
|
|
230
|
-
if (promise instanceof Promise) {
|
|
231
|
-
promise.catch(err => {
|
|
232
|
-
reject(new Error(`catch ${err}, arrayBuffer byteLength: ${arraybuffer ? arraybuffer.byteLength : 0}`));
|
|
233
|
-
});
|
|
234
|
-
}
|
|
235
|
-
});
|
|
236
|
-
this.decodeAudioPromiseMap[name] = promise;
|
|
237
|
-
return promise;
|
|
238
|
-
}
|
|
239
123
|
};
|
|
240
124
|
SoundSystem.systemName = 'SoundSystem';
|
|
241
125
|
SoundSystem = __decorate([
|
|
@@ -256,33 +140,34 @@ class Sound extends eva_js.Component {
|
|
|
256
140
|
volume: 1,
|
|
257
141
|
loop: false,
|
|
258
142
|
seek: 0,
|
|
143
|
+
speed: 1,
|
|
259
144
|
};
|
|
260
|
-
this.playTime = 0;
|
|
261
|
-
this.startTime = 0;
|
|
262
|
-
this.duration = 0;
|
|
263
145
|
this.actionQueue = [];
|
|
146
|
+
this.startTime = 0;
|
|
147
|
+
}
|
|
148
|
+
get systemContext() {
|
|
149
|
+
return pixiSound.sound.context.audioContext;
|
|
150
|
+
}
|
|
151
|
+
get playing() {
|
|
152
|
+
if (!this.buffer)
|
|
153
|
+
return false;
|
|
154
|
+
return this.buffer.isPlaying;
|
|
264
155
|
}
|
|
265
156
|
get muted() {
|
|
266
|
-
|
|
157
|
+
var _a;
|
|
158
|
+
return ((_a = this.buffer) === null || _a === void 0 ? void 0 : _a.muted) || false;
|
|
267
159
|
}
|
|
268
160
|
set muted(v) {
|
|
269
|
-
if (
|
|
270
|
-
|
|
271
|
-
}
|
|
272
|
-
this.gainNode.gain.setValueAtTime(v ? 0 : this.config.volume, 0);
|
|
161
|
+
if (this.buffer)
|
|
162
|
+
this.buffer.muted = v;
|
|
273
163
|
}
|
|
274
164
|
get volume() {
|
|
275
|
-
|
|
165
|
+
var _a;
|
|
166
|
+
return ((_a = this.buffer) === null || _a === void 0 ? void 0 : _a.volume) || 0;
|
|
276
167
|
}
|
|
277
168
|
set volume(v) {
|
|
278
|
-
if (
|
|
279
|
-
|
|
280
|
-
}
|
|
281
|
-
this.config.volume = v;
|
|
282
|
-
if (!this.gainNode) {
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
this.gainNode.gain.setValueAtTime(v, 0);
|
|
169
|
+
if (this.buffer)
|
|
170
|
+
this.buffer.volume = v;
|
|
286
171
|
}
|
|
287
172
|
init(obj) {
|
|
288
173
|
if (!obj) {
|
|
@@ -297,101 +182,43 @@ class Sound extends eva_js.Component {
|
|
|
297
182
|
if (this.state !== 'loaded') {
|
|
298
183
|
this.actionQueue.push(this.play.bind(this));
|
|
299
184
|
}
|
|
300
|
-
this.
|
|
301
|
-
this.createSource();
|
|
302
|
-
if (!this.sourceNode) {
|
|
185
|
+
if (!this.buffer)
|
|
303
186
|
return;
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
this.
|
|
309
|
-
|
|
310
|
-
this.
|
|
311
|
-
this.paused = false;
|
|
312
|
-
this.playing = true;
|
|
313
|
-
this.resetConfig();
|
|
314
|
-
this.endedListener = () => {
|
|
315
|
-
if (!this.sourceNode) {
|
|
316
|
-
return;
|
|
317
|
-
}
|
|
318
|
-
if (this.config.onEnd) {
|
|
319
|
-
this.config.onEnd();
|
|
320
|
-
}
|
|
321
|
-
if (this.playing) {
|
|
322
|
-
this.destroySource();
|
|
323
|
-
}
|
|
324
|
-
};
|
|
325
|
-
this.sourceNode.addEventListener('ended', this.endedListener);
|
|
187
|
+
this.startTime = this.systemContext.currentTime;
|
|
188
|
+
this.buffer.play();
|
|
189
|
+
}
|
|
190
|
+
resume() {
|
|
191
|
+
if (!this.buffer)
|
|
192
|
+
return;
|
|
193
|
+
this.buffer.resume();
|
|
326
194
|
}
|
|
327
195
|
pause() {
|
|
328
|
-
if (this.
|
|
329
|
-
this.actionQueue.push(this.pause.bind(this));
|
|
330
|
-
}
|
|
331
|
-
if (this.paused || !this.playing) {
|
|
196
|
+
if (!this.buffer)
|
|
332
197
|
return;
|
|
333
|
-
|
|
334
|
-
this.paused = true;
|
|
335
|
-
this.playing = false;
|
|
336
|
-
this.config.seek = this.getCurrentTime();
|
|
337
|
-
this.destroySource();
|
|
198
|
+
this.buffer.pause();
|
|
338
199
|
}
|
|
339
200
|
stop() {
|
|
340
|
-
if (this.
|
|
341
|
-
this.actionQueue.push(this.stop.bind(this));
|
|
342
|
-
}
|
|
343
|
-
if (!this.paused && !this.playing) {
|
|
201
|
+
if (!this.buffer)
|
|
344
202
|
return;
|
|
345
|
-
|
|
346
|
-
this.playing = false;
|
|
347
|
-
this.paused = false;
|
|
348
|
-
this.destroySource();
|
|
349
|
-
this.resetConfig();
|
|
203
|
+
this.buffer.stop();
|
|
350
204
|
}
|
|
351
205
|
onload(buffer) {
|
|
352
206
|
this.state = 'loaded';
|
|
353
207
|
this.buffer = buffer;
|
|
354
|
-
this.
|
|
208
|
+
this.buffer.muted = this.config.muted;
|
|
209
|
+
this.buffer.volume = this.config.volume;
|
|
210
|
+
this.buffer.loop = this.config.loop;
|
|
211
|
+
this.buffer.speed = this.config.speed;
|
|
355
212
|
this.actionQueue.forEach(action => action());
|
|
356
213
|
this.actionQueue.length = 0;
|
|
357
214
|
}
|
|
358
215
|
onDestroy() {
|
|
359
216
|
this.actionQueue.length = 0;
|
|
360
|
-
this.destroySource();
|
|
361
|
-
}
|
|
362
|
-
resetConfig() {
|
|
363
|
-
this.config.seek = 0;
|
|
364
|
-
}
|
|
365
|
-
getCurrentTime() {
|
|
366
|
-
if (this.config.loop && this.duration > 0) {
|
|
367
|
-
return (this.systemContext.currentTime - this.playTime) % this.duration;
|
|
368
|
-
}
|
|
369
|
-
return this.systemContext.currentTime - this.playTime;
|
|
370
|
-
}
|
|
371
|
-
createSource() {
|
|
372
|
-
if (!this.systemContext || this.state !== 'loaded') {
|
|
373
|
-
return;
|
|
374
|
-
}
|
|
375
|
-
this.sourceNode = this.systemContext.createBufferSource();
|
|
376
|
-
this.sourceNode.buffer = this.buffer;
|
|
377
|
-
this.sourceNode.loop = this.config.loop;
|
|
378
|
-
if (!this.gainNode) {
|
|
379
|
-
this.gainNode = this.systemContext.createGain();
|
|
380
|
-
this.gainNode.connect(this.systemDestination);
|
|
381
|
-
Object.assign(this, this.config);
|
|
382
|
-
}
|
|
383
|
-
this.sourceNode.connect(this.gainNode);
|
|
384
|
-
}
|
|
385
|
-
destroySource() {
|
|
386
|
-
if (!this.sourceNode)
|
|
387
|
-
return;
|
|
388
|
-
this.sourceNode.removeEventListener('ended', this.endedListener);
|
|
389
|
-
this.sourceNode.stop();
|
|
390
|
-
this.sourceNode.disconnect();
|
|
391
|
-
this.sourceNode = null;
|
|
392
217
|
this.startTime = 0;
|
|
393
|
-
this.
|
|
394
|
-
|
|
218
|
+
if (this.buffer) {
|
|
219
|
+
this.buffer.destroy();
|
|
220
|
+
this.buffer = null;
|
|
221
|
+
}
|
|
395
222
|
}
|
|
396
223
|
}
|
|
397
224
|
Sound.componentName = 'Sound';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@eva/eva.js"),t=require("@ali/pixi-sound"),s=require("pixi.js");function o(e,t,s,o){return new(s||(s=Promise))((function(u,i){function n(e){try{a(o.next(e))}catch(e){i(e)}}function r(e){try{a(o.throw(e))}catch(e){i(e)}}function a(e){e.done?u(e.value):new s((function(t){t(e.value)})).then(n,r)}a((o=o.apply(e,t||[])).next())}))}t.sound.disableAutoPause=!0,t.utils.extensions.push("aac"),t.utils.validateFormats({aac:"audio/aac"}),s.extensions.add(t.soundAsset);let u=class extends e.System{constructor(e){super(),this.autoPauseAndStart=!0,this.components=[],this.audioBufferCache={},Object.assign(this,e),(null==e?void 0:e.useLegacy)&&(t.sound.useLegacy=!0)}resumeAll(){t.sound.resumeAll()}pauseAll(){t.sound.pauseAll()}stopAll(){t.sound.stopAll()}update(){const e=this.componentObserver.clear();for(const t of e)this.componentChanged(t)}onResume(){this.autoPauseAndStart&&this.resumeAll()}onPause(){this.autoPauseAndStart&&this.pauseAll()}onDestroy(){this.components.forEach((e=>{e.onDestroy()})),this.components=[],t.sound.removeAll()}componentChanged(t){return o(this,void 0,void 0,(function*(){"Sound"===t.componentName&&t.type===e.OBSERVER_TYPE.ADD&&this.add(t)}))}add(t){var s,u;return o(this,void 0,void 0,(function*(){const o=t.component;this.components.push(o);try{const{config:t}=o;o.state="loading";const i=yield e.resource.getResource(t.resource);!this.audioBufferCache[i.name]&&(null===(s=null==i?void 0:i.data)||void 0===s?void 0:s.audio)&&(this.audioBufferCache[i.name]=null===(u=null==i?void 0:i.data)||void 0===u?void 0:u.audio),this.audioBufferCache[i.name]&&o.onload(this.audioBufferCache[i.name])}catch(e){this.onError&&this.onError(e)}}))}};u.systemName="SoundSystem",u=
|
|
2
2
|
/*! *****************************************************************************
|
|
3
3
|
Copyright (c) Microsoft Corporation. All rights reserved.
|
|
4
4
|
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
@@ -12,4 +12,5 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
|
|
|
12
12
|
|
|
13
13
|
See the Apache Version 2.0 License for specific language governing permissions
|
|
14
14
|
and limitations under the License.
|
|
15
|
-
***************************************************************************** */
|
|
15
|
+
***************************************************************************** */
|
|
16
|
+
function(e,t,s,o){var u,i=arguments.length,n=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,s):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,s,o);else for(var r=e.length-1;r>=0;r--)(u=e[r])&&(n=(i<3?u(n):i>3?u(t,s,n):u(t,s))||n);return i>3&&n&&Object.defineProperty(t,s,n),n}([e.decorators.componentObserver({Sound:[]})],u);var i=u;class n extends e.Component{constructor(){super(...arguments),this.state="unloaded",this.config={resource:"",autoplay:!1,muted:!1,volume:1,loop:!1,seek:0,speed:1},this.actionQueue=[],this.startTime=0}get systemContext(){return t.sound.context.audioContext}get playing(){return!!this.buffer&&this.buffer.isPlaying}get muted(){var e;return(null===(e=this.buffer)||void 0===e?void 0:e.muted)||!1}set muted(e){this.buffer&&(this.buffer.muted=e)}get volume(){var e;return(null===(e=this.buffer)||void 0===e?void 0:e.volume)||0}set volume(e){this.buffer&&(this.buffer.volume=e)}init(e){e&&(Object.assign(this.config,e),this.config.autoplay&&this.actionQueue.push(this.play.bind(this)))}play(){"loaded"!==this.state&&this.actionQueue.push(this.play.bind(this)),this.buffer&&(this.startTime=this.systemContext.currentTime,this.buffer.play())}resume(){this.buffer&&this.buffer.resume()}pause(){this.buffer&&this.buffer.pause()}stop(){this.buffer&&this.buffer.stop()}onload(e){this.state="loaded",this.buffer=e,this.buffer.muted=this.config.muted,this.buffer.volume=this.config.volume,this.buffer.loop=this.config.loop,this.buffer.speed=this.config.speed,this.actionQueue.forEach((e=>e())),this.actionQueue.length=0}onDestroy(){this.actionQueue.length=0,this.startTime=0,this.buffer&&(this.buffer.destroy(),this.buffer=null)}}n.componentName="Sound";var r=n;exports.Sound=r,exports.SoundSystem=i;
|
package/dist/plugin-sound.d.ts
CHANGED
|
@@ -1,37 +1,29 @@
|
|
|
1
1
|
import { Component } from '@eva/eva.js';
|
|
2
2
|
import { ComponentChanged } from '@eva/eva.js';
|
|
3
|
+
import { Sound as Sound_2 } from '@ali/pixi-sound';
|
|
3
4
|
import { System } from '@eva/eva.js';
|
|
4
5
|
|
|
5
6
|
export declare class Sound extends Component<SoundParams> {
|
|
6
7
|
static componentName: string;
|
|
7
|
-
systemContext: AudioContext;
|
|
8
|
+
get systemContext(): AudioContext;
|
|
8
9
|
systemDestination: GainNode;
|
|
9
|
-
playing: boolean;
|
|
10
|
+
get playing(): boolean;
|
|
10
11
|
state: 'unloaded' | 'loading' | 'loaded';
|
|
11
12
|
config: SoundParams;
|
|
12
|
-
private buffer;
|
|
13
|
-
private sourceNode;
|
|
14
|
-
private gainNode;
|
|
15
|
-
private paused;
|
|
16
|
-
private playTime;
|
|
17
|
-
private startTime;
|
|
18
|
-
private duration;
|
|
19
13
|
private actionQueue;
|
|
20
|
-
|
|
14
|
+
startTime: number;
|
|
15
|
+
private buffer;
|
|
21
16
|
get muted(): boolean;
|
|
22
17
|
set muted(v: boolean);
|
|
23
18
|
get volume(): number;
|
|
24
19
|
set volume(v: number);
|
|
25
20
|
init(obj?: SoundParams): void;
|
|
26
21
|
play(): void;
|
|
22
|
+
resume(): void;
|
|
27
23
|
pause(): void;
|
|
28
24
|
stop(): void;
|
|
29
|
-
onload(buffer:
|
|
25
|
+
onload(buffer: Sound_2): void;
|
|
30
26
|
onDestroy(): void;
|
|
31
|
-
private resetConfig;
|
|
32
|
-
private getCurrentTime;
|
|
33
|
-
private createSource;
|
|
34
|
-
private destroySource;
|
|
35
27
|
}
|
|
36
28
|
|
|
37
29
|
declare interface SoundParams {
|
|
@@ -41,42 +33,31 @@ declare interface SoundParams {
|
|
|
41
33
|
volume?: number;
|
|
42
34
|
loop?: boolean;
|
|
43
35
|
seek?: number;
|
|
36
|
+
speed?: number;
|
|
44
37
|
duration?: number;
|
|
45
38
|
onEnd?: () => void;
|
|
46
39
|
}
|
|
47
40
|
|
|
48
41
|
export declare class SoundSystem extends System {
|
|
49
42
|
static systemName: string;
|
|
50
|
-
private ctx;
|
|
51
|
-
private gainNode;
|
|
52
43
|
private autoPauseAndStart;
|
|
53
44
|
private onError;
|
|
54
45
|
private components;
|
|
55
|
-
private pausedComponents;
|
|
56
46
|
private audioBufferCache;
|
|
57
|
-
private decodeAudioPromiseMap;
|
|
58
|
-
get muted(): boolean;
|
|
59
|
-
set muted(v: boolean);
|
|
60
|
-
get volume(): number;
|
|
61
|
-
set volume(v: number);
|
|
62
|
-
get audioLocked(): boolean;
|
|
63
47
|
constructor(obj?: SoundSystemParams);
|
|
64
48
|
resumeAll(): void;
|
|
65
49
|
pauseAll(): void;
|
|
66
50
|
stopAll(): void;
|
|
67
|
-
init(): void;
|
|
68
51
|
update(): void;
|
|
69
52
|
onResume(): void;
|
|
70
53
|
onPause(): void;
|
|
71
54
|
onDestroy(): void;
|
|
72
55
|
componentChanged(changed: ComponentChanged): Promise<void>;
|
|
73
|
-
private setupAudioContext;
|
|
74
|
-
private unlockAudio;
|
|
75
56
|
private add;
|
|
76
|
-
private decodeAudioData;
|
|
77
57
|
}
|
|
78
58
|
|
|
79
59
|
declare interface SoundSystemParams {
|
|
60
|
+
useLegacy?: boolean;
|
|
80
61
|
autoPauseAndStart?: boolean;
|
|
81
62
|
onError: (error: any) => void;
|
|
82
63
|
}
|