UNPKG

@audiowave/react

Version:

React audio visualization component

24 lines (23 loc) 22.2 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react");var Ae={exports:{}},fe={};/** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var ve;function De(){if(ve)return fe;ve=1;var e=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function n(i,o,a){var f=null;if(a!==void 0&&(f=""+a),o.key!==void 0&&(f=""+o.key),"key"in o){a={};for(var E in o)E!=="key"&&(a[E]=o[E])}else a=o;return o=a.ref,{$$typeof:e,type:i,key:f,ref:o!==void 0?o:null,props:a}}return fe.Fragment=r,fe.jsx=n,fe.jsxs=n,fe}var de={};/** * @license React * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var xe;function ke(){return xe||(xe=1,process.env.NODE_ENV!=="production"&&function(){function e(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===x?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case C:return"Fragment";case X:return"Profiler";case B:return"StrictMode";case W:return"Suspense";case oe:return"SuspenseList";case A:return"Activity"}if(typeof t=="object")switch(typeof t.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),t.$$typeof){case M:return"Portal";case b:return(t.displayName||"Context")+".Provider";case v:return(t._context.displayName||"Context")+".Consumer";case U:var c=t.render;return t=t.displayName,t||(t=c.displayName||c.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Y:return c=t.displayName||null,c!==null?c:e(t.type)||"Memo";case P:c=t._payload,t=t._init;try{return e(t(c))}catch{}}return null}function r(t){return""+t}function n(t){try{r(t);var c=!1}catch{c=!0}if(c){c=console;var h=c.error,S=typeof Symbol=="function"&&Symbol.toStringTag&&t[Symbol.toStringTag]||t.constructor.name||"Object";return h.call(c,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",S),r(t)}}function i(t){if(t===C)return"<>";if(typeof t=="object"&&t!==null&&t.$$typeof===P)return"<...>";try{var c=e(t);return c?"<"+c+">":"<...>"}catch{return"<...>"}}function o(){var t=O.A;return t===null?null:t.getOwner()}function a(){return Error("react-stack-top-frame")}function f(t){if(z.call(t,"key")){var c=Object.getOwnPropertyDescriptor(t,"key").get;if(c&&c.isReactWarning)return!1}return t.key!==void 0}function E(t,c){function h(){J||(J=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",c))}h.isReactWarning=!0,Object.defineProperty(t,"key",{get:h,configurable:!0})}function u(){var t=e(this.type);return re[t]||(re[t]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),t=this.props.ref,t!==void 0?t:null}function d(t,c,h,S,k,_,ie,Q){return h=_.ref,t={$$typeof:j,type:t,key:c,props:_,_owner:k},(h!==void 0?h:null)!==null?Object.defineProperty(t,"ref",{enumerable:!1,get:u}):Object.defineProperty(t,"ref",{enumerable:!1,value:null}),t._store={},Object.defineProperty(t._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(t,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(t,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:ie}),Object.defineProperty(t,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Q}),Object.freeze&&(Object.freeze(t.props),Object.freeze(t)),t}function R(t,c,h,S,k,_,ie,Q){var T=c.children;if(T!==void 0)if(S)if(p(T)){for(S=0;S<T.length;S++)y(T[S]);Object.freeze&&Object.freeze(T)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else y(T);if(z.call(c,"key")){T=e(t);var V=Object.keys(c).filter(function(ce){return ce!=="key"});S=0<V.length?"{key: someKey, "+V.join(": ..., ")+": ...}":"{key: someKey}",Z[T+S]||(V=0<V.length?"{"+V.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`,S,T,V,T),Z[T+S]=!0)}if(T=null,h!==void 0&&(n(h),T=""+h),f(c)&&(n(c.key),T=""+c.key),"key"in c){h={};for(var K in c)K!=="key"&&(h[K]=c[K])}else h=c;return T&&E(h,typeof t=="function"?t.displayName||t.name||"Unknown":t),d(t,T,_,k,o(),h,ie,Q)}function y(t){typeof t=="object"&&t!==null&&t.$$typeof===j&&t._store&&(t._store.validated=1)}var N=s,j=Symbol.for("react.transitional.element"),M=Symbol.for("react.portal"),C=Symbol.for("react.fragment"),B=Symbol.for("react.strict_mode"),X=Symbol.for("react.profiler"),v=Symbol.for("react.consumer"),b=Symbol.for("react.context"),U=Symbol.for("react.forward_ref"),W=Symbol.for("react.suspense"),oe=Symbol.for("react.suspense_list"),Y=Symbol.for("react.memo"),P=Symbol.for("react.lazy"),A=Symbol.for("react.activity"),x=Symbol.for("react.client.reference"),O=N.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,z=Object.prototype.hasOwnProperty,p=Array.isArray,I=console.createTask?console.createTask:function(){return null};N={"react-stack-bottom-frame":function(t){return t()}};var J,re={},ne=N["react-stack-bottom-frame"].bind(N,a)(),L=I(i(a)),Z={};de.Fragment=C,de.jsx=function(t,c,h,S,k){var _=1e4>O.recentlyCreatedOwnerStacks++;return R(t,c,h,!1,S,k,_?Error("react-stack-top-frame"):ne,_?I(i(t)):L)},de.jsxs=function(t,c,h,S,k){var _=1e4>O.recentlyCreatedOwnerStacks++;return R(t,c,h,!0,S,k,_?Error("react-stack-top-frame"):ne,_?I(i(t)):L)}}()),de}process.env.NODE_ENV==="production"?Ae.exports=De():Ae.exports=ke();var $=Ae.exports,H=(e=>(e.MEDIA_NOT_SUPPORTED="MEDIA_NOT_SUPPORTED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.AUDIO_CONTEXT_ERROR="AUDIO_CONTEXT_ERROR",e.SHARED_BUFFER_ERROR="SHARED_BUFFER_ERROR",e.RENDER_ERROR="RENDER_ERROR",e.CONFIGURATION_ERROR="CONFIGURATION_ERROR",e.INVALID_STATE="INVALID_STATE",e.ADAPTER_ERROR="ADAPTER_ERROR",e.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",e))(H||{});class q extends Error{constructor(r,n,i){super(n),this.type=r,this.originalError=i,this.name="AudioWaveError"}}const _e=256;class Fe{constructor(){this.recentMax=0,this.longTermMax=0,this.history=[],this.maxHistoryLength=60}scale(r){this.history.push(r),this.history.length>this.maxHistoryLength&&this.history.shift(),this.recentMax=Math.max(this.recentMax*.95,r),this.longTermMax=this.longTermMax*.998+r*.002;const n=Math.max(this.recentMax*.6+this.longTermMax*.4,30),i=r/n*180;return Math.min(255,i*(1-i/400))}}function je(e){let r=0;const n=128;for(let u=0;u<e.length;u++){const d=e[u]-n;r+=d*d}const o=Math.sqrt(r/e.length)/128,a=.002,f=.008;let E;if(o<a)E=1;else if(o<f)E=1+((o-a)/(f-a))**2.5*8;else{const u=Math.log10(o+.001)+3;E=Math.max(10,u*85)}return Math.max(1,Math.min(255,E))}let he=null;function Ue(e,r="transparent"){const n=e.getContext("2d");if(!n)return null;const{width:i,height:o}=e,a=i/2,f=o/2;return n.clearRect(0,0,i,o),r!=="transparent"&&(n.fillStyle=r,n.fillRect(0,0,i,o)),{context:n,width:i,height:o,halfWidth:a,halfHeight:f}}function Pe({context:e,x:r,y:n,width:i,height:o,color:a,rounded:f}){e.fillStyle=a,f>0?(e.beginPath(),e.roundRect(r,n,i,o,f),e.fill()):e.fillRect(r,n,i,o)}const ze=({canvas:e,backgroundColor:r})=>{const n=e.height,i=e.width,o=Math.round(i/2),a=e.getContext("2d");return a?(a.clearRect(0,0,i,n),r!=="transparent"&&(a.fillStyle=r,a.fillRect(0,0,i,n)),{context:a,height:n,width:i,halfWidth:o}):null},pe=({context:e,color:r,rounded:n,x:i,y:o,w:a,h:f})=>{e.fillStyle=r,e.beginPath(),e.roundRect?(e.roundRect(i,o,a,f,n),e.fill()):e.fillRect(i,o,a,f)},Le=({context:e,color:r,rounded:n,width:i,height:o,barWidth:a})=>{pe({context:e,color:r,rounded:n,x:i/2+a/2,y:o/2-1,h:2,w:i-(i/2+a/2)})},we=({audioData:e,unit:r,index:n,index2:i,canvas:o,isAudioInProgress:a,isPausedAudio:f,picks:E,backgroundColor:u,barWidth:d,mainBarColor:R,secondaryBarColor:y,rounded:N,animateCurrentPick:j,fullscreen:M,gain:C=1,amplitudeMode:B="peak"})=>{const X=ze({canvas:o,backgroundColor:u});if(!X)return;const{context:v,height:b,width:U,halfWidth:W}=X;if(e!=null&&e.length&&a){let Y=0;switch(B==="adaptive"?he||(he=new Fe):he=null,B){case"rms":{const A=je(e),x=Math.max(.1,Math.min(10,C));Y=Math.min(255,A*x);break}case"adaptive":{let A=0;const x=128;for(let p=0;p<e.length;p++){const I=Math.abs(e[p]-x);I>A&&(A=I)}const O=he.scale(A*2),z=Math.max(.1,Math.min(10,C));Y=Math.min(255,O*z);break}default:{let A=0;const x=128;for(let p=0;p<e.length;p++){const I=Math.abs(e[p]-x);I>A&&(A=I)}const O=A*2,z=Math.max(.1,Math.min(10,C));Y=Math.min(255,O*z);break}}if(!f){if(i.current>=d){i.current=0;const x=Y/_e*100,O=(100-x)/2,z=n.current===d?{startY:O,barHeight:x}:null;n.current>=r?n.current=d:n.current+=d,E.length>(M?U:W)/d&&E.pop(),E.unshift(z)}i.current+=1}if(!M&&oe(),j&&!f){const x=Y/_e*b;pe({context:v,rounded:N,color:R,x:M?U:W,y:(b-x)/2,h:x,w:d})}let P=(M?U:W)-i.current;for(const A of E)A&&pe({context:v,color:R,rounded:N,x:P,y:A.startY*b/100>b/2-1?b/2-1:A.startY*b/100,h:A.barHeight*b/100>2?A.barHeight*b/100:2,w:d}),P-=d}else E.length=0;function oe(){Le({context:v,color:y,rounded:N,width:U,height:b,barWidth:d})}};function Ce(e,r,n,i,o=1){if(e.style.width=`${r}px`,e.style.height=`${n}px`,e.width=r,e.height=n,i&&i!=="transparent"){const a=e.getContext("2d");a&&(a.fillStyle=i,a.fillRect(0,0,r,n))}}const Oe=s.forwardRef(({source:e,width:r=D.width,height:n=D.height,backgroundColor:i=D.backgroundColor,barColor:o=D.barColor,secondaryBarColor:a=D.secondaryBarColor,barWidth:f=D.barWidth,gap:E=D.gap,rounded:u=D.rounded,showBorder:d=!1,borderColor:R="#333333",borderWidth:y=1,borderRadius:N=0,speed:j=D.speed,animateCurrentPick:M=D.animateCurrentPick,fullscreen:C=D.fullscreen,gain:B=1,amplitudeMode:X="peak",isPaused:v=!1,placeholder:b,showPlaceholderBackground:U=!0,customRenderer:W,className:oe,canvasClassName:Y,onStateChange:P,onRenderStart:A,onRenderStop:x,onError:O},z)=>{const p=s.useRef(null),I=s.useRef(null),J=s.useRef(null),re=s.useRef(null),ne=s.useRef(null),L=s.useRef(null),Z=s.useRef(null),[t,c]=s.useState(window.innerWidth),h=t<768,S=Math.trunc(j),k=Math.trunc(E),_=Math.trunc(h&&k>0?f+1:f),ie=_+k*_,Q=s.useRef([]),T=s.useRef(S),V=s.useRef(_),K=s.useRef(_),[ce,be]=s.useState({width:0,height:0}),[ee,ye]=s.useState(new Uint8Array(0)),[F,Me]=s.useState("idle"),ue=s.useRef("idle"),Ne=s.useRef(null),G=s.useCallback(l=>{Me(l),ue.current=l,P==null||P(l)},[P]),Se=s.useCallback(()=>{Q.current.length=0,V.current=0,K.current=0,ye(new Uint8Array(0))},[]);s.useEffect(()=>{const l=()=>{c(window.innerWidth)};return window.addEventListener("resize",l),()=>window.removeEventListener("resize",l)},[]);const Ee=s.useCallback(()=>{if(!L.current||!e)return;if(ue.current==="visualizing"&&!v&&typeof e.getAudioData=="function"){const m=e.getAudioData();if(m&&m.length>0){const w=m.reduce((ae,se)=>ae+se,0)/m.length;if(w>=0&&w<=255){const ae=Math.min(m.length,L.current.length);for(let se=0;se<ae;se++)L.current[se]=m[se];ye(new Uint8Array(L.current))}}}Z.current=requestAnimationFrame(Ee)},[v,e]),Te=s.useCallback((l,m)=>{const w=new q(H.RENDER_ERROR,`${m}: ${l.message}`,l);O==null||O(w),console.error("AudioWave Error:",w)},[O]),ge=s.useCallback(async()=>{if(e)try{if(typeof e.getAudioData!="function"||typeof e.isActive!="function")throw new Error("Audio source must implement getAudioData() and isActive() methods");Ne.current=e,L.current=new Uint8Array(1024),L.current.fill(128),G("visualizing"),A==null||A(),Ee()}catch(l){Te(l instanceof Error?l:new Error(String(l)),"Failed to set up audio source")}},[e,Te,A,Ee,G]),le=s.useCallback((l=!1)=>{var m,w;if(Z.current&&(cancelAnimationFrame(Z.current),Z.current=null),ne.current&&(ne.current.disconnect(),ne.current=null),re.current&&(re.current.disconnect(),re.current=null),J.current&&J.current.state!=="closed"){try{(w=(m=J.current).close)==null||w.call(m)}catch(te){console.warn("Error closing audio context:",te)}J.current=null}l||(Ne.current=null),l||(L.current=null,G("idle"),x==null||x())},[x,G]);s.useLayoutEffect(()=>{if(p.current){if(T.current>=S||!ee.length){T.current=ee.length?0:S;const l=(e==null?void 0:e.isActive())??!1;if(W){const m={canvas:p.current,context:p.current.getContext("2d"),audioData:ee,isActive:l,timestamp:performance.now(),dimensions:{width:p.current.width,height:p.current.height}};W(m)}else we({audioData:ee,unit:ie,index:V,index2:K,canvas:p.current,isAudioInProgress:l||F==="paused"||v,isPausedAudio:F==="paused"||v,picks:Q.current,backgroundColor:i,barWidth:_,mainBarColor:o,secondaryBarColor:a,rounded:u,animateCurrentPick:M,fullscreen:C,gain:B,amplitudeMode:X});if(d&&p.current){const m=p.current.getContext("2d");m&&(m.strokeStyle=R,m.lineWidth=y,N>0&&m.roundRect?(m.beginPath(),m.roundRect(y/2,y/2,p.current.width-y,p.current.height-y,N),m.stroke()):m.strokeRect(0,0,p.current.width,p.current.height))}}T.current+=1}},[ee,_,i,o,a,u,C,d,R,y,N,S,ie,v,e,W,F,M,B,X]);const Re=s.useCallback(()=>{const l=p.current,m=I.current;if(!l||!m)return;let w,te;if(typeof r=="string")if(r.endsWith("%")){const ae=Number.parseFloat(r);w=m.clientWidth*ae/100}else w=Number.parseInt(r,10)||800;else w=r;te=n,(ce.width!==w||ce.height!==te)&&(Ce(l,w,te,i),be({width:w,height:te}))},[r,n,ce,i]);return s.useEffect(()=>(e?ge():v||le(),()=>{const l=v||ue.current==="paused";le(l)}),[e,ge,le,v]),s.useEffect(()=>{Re();const l=new ResizeObserver(Re);return I.current&&l.observe(I.current),()=>{l.disconnect()}},[Re]),s.useEffect(()=>()=>{le(!1),Q.current.length=0,V.current=0,K.current=0},[le]),s.useImperativeHandle(z,()=>({pause:()=>{const l=ue.current;(l==="visualizing"||l==="idle"&&e)&&G("paused")},resume:()=>{const l=ue.current;(l==="paused"||l==="idle"&&e)&&G("visualizing")},clear:()=>{Se()},isPaused:()=>F==="paused",getState:()=>F,getAudioData:()=>ee}),[F,G,Se,ee,e]),$.jsxs("div",{ref:I,className:oe,style:{width:typeof r=="string"&&r.endsWith("%")?"100%":typeof r=="string"?r:`${r}px`,height:`${n}px`,position:"relative",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:!e&&!v&&F!=="paused"&&U?i:"transparent",border:!e&&!v&&F!=="paused"&&U&&d?`${y}px solid ${R}`:"none",borderRadius:!e&&!v&&F!=="paused"&&U&&N>0?`${N}px`:"0"},children:[$.jsx("canvas",{ref:p,className:Y,style:{width:typeof r=="string"&&r.endsWith("%")?r:"100%",height:"100%",display:e||v||F==="paused"?"block":"none",borderRadius:N>0?`${N}px`:"0"}}),!e&&!v&&F!=="paused"&&$.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:"#666",opacity:.5,pointerEvents:"none"},children:b||$.jsxs("svg",{width:48,height:48,viewBox:"0 0 24 24",fill:"currentColor","aria-label":"Audio waveform placeholder",children:[$.jsx("title",{children:"Audio waveform placeholder"}),$.jsx("rect",{x:"2",y:"8",width:"2",height:"8",rx:"1"}),$.jsx("rect",{x:"6",y:"4",width:"2",height:"16",rx:"1"}),$.jsx("rect",{x:"10",y:"6",width:"2",height:"12",rx:"1"}),$.jsx("rect",{x:"14",y:"2",width:"2",height:"20",rx:"1"}),$.jsx("rect",{x:"18",y:"7",width:"2",height:"10",rx:"1"})]})})]})});Oe.displayName="AudioWave";var g=(e=>(e.INACTIVE="inactive",e.CONNECTING="connecting",e.ACTIVE="active",e.ERROR="error",e))(g||{});class Ie{constructor(r={}){this.audioContext=null,this.analyserNode=null,this.sourceNode=null,this.audioData=null,this.state=g.INACTIVE,this.mediaStream=null,this.inputAudioNode=null,this.options={fftSize:2048,smoothingTimeConstant:0,...r}}async initializeFromMediaStream(r){if(this.state!==g.INACTIVE)throw new q(H.INVALID_STATE,"WebAudioSource is already initialized");this.state=g.CONNECTING,this.mediaStream=r;try{await this.setupWebAudio(),this.sourceNode=this.audioContext.createMediaStreamSource(r),this.connectNodes(),this.state=g.ACTIVE}catch(n){throw this.cleanup(),this.state=g.ERROR,new q(H.AUDIO_CONTEXT_ERROR,"Failed to initialize from MediaStream",n instanceof Error?n:new Error(String(n)))}}async initializeFromMediaElement(r){if(this.state!==g.INACTIVE)throw new q(H.INVALID_STATE,"WebAudioSource is already initialized");this.state=g.CONNECTING;try{await this.setupWebAudio(),this.sourceNode=this.audioContext.createMediaElementSource(r),this.sourceNode.connect(this.audioContext.destination),this.connectNodes(),this.state=g.ACTIVE}catch(n){throw this.cleanup(),this.state=g.ERROR,new q(H.AUDIO_CONTEXT_ERROR,"Failed to initialize from HTMLMediaElement",n instanceof Error?n:new Error(String(n)))}}async initializeFromAudioNode(r){if(this.state!==g.INACTIVE)throw new q(H.INVALID_STATE,"WebAudioSource is already initialized");this.state=g.CONNECTING,this.inputAudioNode=r;try{this.audioContext=r.context,this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.setupAnalyser(),this.sourceNode=r,this.connectNodes(),this.state=g.ACTIVE}catch(n){throw this.cleanup(),this.state=g.ERROR,new q(H.AUDIO_CONTEXT_ERROR,"Failed to initialize from AudioNode",n instanceof Error?n:new Error(String(n)))}}getAudioData(){return this.state!==g.ACTIVE||!this.analyserNode||!this.audioData?null:(this.analyserNode.getByteTimeDomainData(this.audioData),new Uint8Array(this.audioData))}getTimeDomainData(){if(this.state!==g.ACTIVE||!this.analyserNode||!this.audioData)return null;const r=new Uint8Array(this.analyserNode.frequencyBinCount);return this.analyserNode.getByteTimeDomainData(r),r}getFrequencyData(){if(this.state!==g.ACTIVE||!this.analyserNode||!this.audioData)return null;const r=new Uint8Array(this.analyserNode.frequencyBinCount);return this.analyserNode.getByteFrequencyData(r),r}isActive(){return this.state===g.ACTIVE}getState(){return this.state}getConfig(){return{fftSize:this.options.fftSize}}destroy(){this.cleanup(),this.state=g.INACTIVE}async setupWebAudio(){this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.setupAnalyser()}setupAnalyser(){this.audioContext&&(this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=this.options.fftSize,this.analyserNode.smoothingTimeConstant=this.options.smoothingTimeConstant,this.audioData=new Uint8Array(new ArrayBuffer(this.analyserNode.fftSize)))}connectNodes(){this.sourceNode&&this.analyserNode&&this.sourceNode.connect(this.analyserNode)}cleanup(){this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.sourceNode&&this.sourceNode!==this.inputAudioNode&&this.sourceNode.disconnect(),this.sourceNode=null,this.analyserNode&&(this.analyserNode.disconnect(),this.analyserNode=null),this.audioContext&&!this.inputAudioNode&&this.audioContext.state!=="closed"&&this.audioContext.close().catch(console.warn),this.audioContext=null,this.inputAudioNode=null,this.audioData=null}}function me(e={}){const[r,n]=s.useState(null),[i,o]=s.useState(null),a=s.useRef(null),f=s.useRef(!1),E=s.useCallback(async u=>{var d;if(!u)return null;if(typeof u=="object"&&"getAudioData"in u&&"isActive"in u)return f.current=!0,u;try{const R=new Ie;if(u instanceof MediaStream)await R.initializeFromMediaStream(u);else if(u instanceof HTMLMediaElement||u instanceof HTMLAudioElement||u instanceof HTMLVideoElement)await R.initializeFromMediaElement(u);else if("context"in u&&typeof u.connect=="function")await R.initializeFromAudioNode(u);else throw new Error(`Unsupported audio source type: ${typeof u}`);return a.current=R,f.current=!1,R}catch(R){const y=R instanceof Error?R:new Error(String(R));return o(y),(d=e.onError)==null||d.call(e,y),null}},[e]);return s.useEffect(()=>{let u=!0;return(async()=>{var R;try{o(null),a.current&&!f.current&&(a.current.destroy(),a.current=null);const y=await E(e.source??null);u&&n(y)}catch(y){if(u){const N=y instanceof Error?y:new Error(String(y));o(N),(R=e.onError)==null||R.call(e,N)}}})(),()=>{u=!1}},[e.source,E,e]),s.useEffect(()=>()=>{a.current&&!f.current&&a.current.destroy()},[]),{source:r,error:i}}function Ve(e,r={}){return me({...r,source:e})}function $e(e,r={}){return me({...r,source:e})}function We(e,r={}){return me({...r,source:e})}function Ye(e){const{provider:r,deviceId:n="default"}=e,[i,o]=s.useState("active"),[a,f]=s.useState(null),E=s.useRef(null),u=s.useRef(null),d=i==="active";s.useEffect(()=>{var M;if(!r){f("Audio provider not available");return}const y={getAudioData:()=>u.current,isActive:()=>i==="active"};E.current=y;const N=r.onAudioData(C=>{u.current=C}),j=(M=r.onAudioError)==null?void 0:M.call(r,C=>{f(C),o("idle")});return()=>{N==null||N(),j==null||j(),u.current=null}},[r,i]);const R=s.useCallback(()=>{f(null)},[]);return{status:i,isActive:d,source:E.current,error:a,deviceId:n,clearError:R}}const Ge="0.1.0",He={WEB_AUDIO:typeof AudioContext<"u"||typeof globalThis.webkitAudioContext<"u",MEDIA_STREAM:typeof navigator<"u"&&"mediaDevices"in navigator,SHARED_ARRAY_BUFFER:typeof SharedArrayBuffer<"u",CANVAS_2D:typeof CanvasRenderingContext2D<"u",ANIMATION_FRAME:typeof requestAnimationFrame<"u"},qe={fftSize:2048},D={width:"100%",height:200,backgroundColor:"transparent",barColor:"#ffffff",secondaryBarColor:"#5e5e5e",barWidth:2,gap:1,rounded:0,speed:3,animateCurrentPick:!0,fullscreen:!1,onlyActive:!1,amplitudeMode:"peak"};exports.AudioSourceState=g;exports.AudioWave=Oe;exports.AudioWaveError=q;exports.AudioWaveErrorType=H;exports.DEFAULT_AUDIO_CONFIG=qe;exports.DEFAULT_VISUALIZER_PROPS=D;exports.FEATURES=He;exports.VERSION=Ge;exports.WebAudioSource=Ie;exports.drawByLiveStream=we;exports.renderBar=Pe;exports.resizeCanvas=Ce;exports.setupCanvas=Ue;exports.useAudioNodeSource=We;exports.useCustomAudio=Ye;exports.useMediaAudio=me;exports.useMediaElementSource=$e;exports.useMediaStreamSource=Ve; //# sourceMappingURL=index.cjs.js.map