import{L as r}from"./index-fe5hJ7Kl.js";class l{constructor(t={}){this.options=t,this.logger=r.create("AudioAnalyzer"),this.audioContext=null,this.analyser=null,this.source=null,this.animationId=null,this._disposed=!1,this.frequencyData=new Uint8Array(0),this.timeDomainData=new Uint8Array(0)}get disposed(){return this._disposed}connect(t){this.disconnect(),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.options.fftSize??256,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant??.8,this.analyser.minDecibels=this.options.minDecibels??-90,this.analyser.maxDecibels=this.options.maxDecibels??-10,this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.timeDomainData=new Uint8Array(this.analyser.frequencyBinCount),this.source=this.audioContext.createMediaStreamSource(t),this.source.connect(this.analyser),this.logger.debug("Connected to stream")}disconnect(){this.source&&(this.source.disconnect(),this.source=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.analyser=null,this.stopMonitoring()}getLevel(){if(!this.analyser)return{volume:0,peak:0,rms:0,frequencyData:new Uint8Array(0)};this.analyser.getByteFrequencyData(this.frequencyData),this.analyser.getByteTimeDomainData(this.timeDomainData);let t=0,e=0;for(let i=0;i<this.frequencyData.length;i++)t+=this.frequencyData[i],e=Math.max(e,this.frequencyData[i]);const a=t/this.frequencyData.length;let s=0;for(let i=0;i<this.timeDomainData.length;i++){const n=(this.timeDomainData[i]-128)/128;s+=n*n}const o=Math.sqrt(s/this.timeDomainData.length);return{volume:Math.min(100,a*1.5),peak:e/255*100,rms:o*100,frequencyData:Uint8Array.from(this.frequencyData)}}startMonitoring(t){this.stopMonitoring();const e=()=>{this._disposed||(t(this.getLevel()),this.animationId=requestAnimationFrame(e))};this.animationId=requestAnimationFrame(e)}stopMonitoring(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}async suspend(){this.audioContext?.state==="running"&&await this.audioContext.suspend()}async resume(){this.audioContext?.state==="suspended"&&await this.audioContext.resume()}dispose(){this._disposed||(this._disposed=!0,this.disconnect(),this.logger.debug("Disposed"))}}export{l as A};
