@animech-public/playcanvas
Version:
PlayCanvas WebGL game engine
2 lines (1 loc) • 2.42 kB
JavaScript
import{EventHandler as e}from"../../core/event-handler.js";import{math as t}from"../../core/math/math.js";import{Channel as s}from"../audio/channel.js";import{Channel3d as n}from"../audio/channel3d.js";import{Listener as o}from"./listener.js";const i="running",r=["click","touchstart","mousedown"];class u extends e{constructor(){super(),this._context=null,this.AudioContext="undefined"!=typeof AudioContext&&AudioContext||"undefined"!=typeof webkitAudioContext&&webkitAudioContext,this.AudioContext,this._unlockHandlerFunc=this._unlockHandler.bind(this),this._userSuspended=!1,this.listener=new o(this),this._volume=1}set volume(e){e=t.clamp(e,0,1),this._volume=e,this.fire("volumechange",e)}get volume(){return this._volume}get suspended(){return this._userSuspended}get context(){return!this._context&&this.AudioContext&&(this._context=new this.AudioContext,this._context.state!==i&&this._registerUnlockListeners()),this._context}suspend(){this._userSuspended||(this._userSuspended=!0,this._context&&this._context.state===i&&this._suspend())}resume(){this._userSuspended&&(this._userSuspended=!1,this._context&&this._context.state!==i&&this._resume())}destroy(){var e;(this.fire("destroy"),this._context)&&(this._removeUnlockListeners(),null==(e=this._context)||e.close(),this._context=null)}playSound(e,t={}){let n=null;return s&&(n=new s(this,e,t),n.play()),n}playSound3d(e,t,s={}){let o=null;return n&&(o=new n(this,e,s),o.setPosition(t),s.volume&&o.setVolume(s.volume),s.loop&&o.setLoop(s.loop),s.maxDistance&&o.setMaxDistance(s.maxDistance),s.minDistance&&o.setMinDistance(s.minDistance),s.rollOffFactor&&o.setRollOffFactor(s.rollOffFactor),s.distanceModel&&o.setDistanceModel(s.distanceModel),o.play()),o}_resume(){this._context.resume().then((()=>{const e=this._context.createBufferSource();e.buffer=this._context.createBuffer(1,1,this._context.sampleRate),e.connect(this._context.destination),e.start(0),e.onended=t=>{e.disconnect(0),this.fire("resume")}}),(e=>{})).catch((e=>{}))}_suspend(){this._context.suspend().then((()=>{this.fire("suspend")}),(e=>{})).catch((e=>{}))}_unlockHandler(){this._removeUnlockListeners(),this._userSuspended||this._context.state===i||this._resume()}_registerUnlockListeners(){r.forEach((e=>{window.addEventListener(e,this._unlockHandlerFunc,!1)}))}_removeUnlockListeners(){r.forEach((e=>{window.removeEventListener(e,this._unlockHandlerFunc,!1)}))}}export{u as SoundManager};