UNPKG

@tecsinapse/react-audio-visualize

Version:

An audio visualizer for React. Provides separate components to visualize both live audio and audio blobs.

32 lines (29 loc) 14.3 kB
(function(P,x){typeof exports=="object"&&typeof module<"u"?x(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],x):(P=typeof globalThis<"u"?globalThis:P||self,x(P.AudioVisualize={},P.React))})(this,function(P,x){"use strict";var X={exports:{}},W={};/** * @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 re;function Re(){if(re)return W;re=1;var o=Symbol.for("react.transitional.element"),l=Symbol.for("react.fragment");function p(w,u,i){var m=null;if(i!==void 0&&(m=""+i),u.key!==void 0&&(m=""+u.key),"key"in u){i={};for(var a in u)a!=="key"&&(i[a]=u[a])}else i=u;return u=i.ref,{$$typeof:o,type:w,key:m,ref:u!==void 0?u:null,props:i}}return W.Fragment=l,W.jsx=p,W.jsxs=p,W}var F={};/** * @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 ne;function Te(){return ne||(ne=1,process.env.NODE_ENV!=="production"&&function(){function o(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Ne?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Y:return"Fragment";case O:return"Portal";case ue:return"Profiler";case se:return"StrictMode";case I:return"Suspense";case Z:return"SuspenseList"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case le:return(e.displayName||"Context")+".Provider";case ce:return(e._context.displayName||"Context")+".Consumer";case D:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Q:return t=e.displayName||null,t!==null?t:o(e.type)||"Memo";case K:t=e._payload,e=e._init;try{return o(e(t))}catch{}}return null}function l(e){return""+e}function p(e){try{l(e);var t=!1}catch{t=!0}if(t){t=console;var r=t.error,c=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return r.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",c),l(e)}}function w(){}function u(){if(G===0){de=console.log,Ee=console.info,me=console.warn,ve=console.error,ge=console.group,be=console.groupCollapsed,he=console.groupEnd;var e={configurable:!0,enumerable:!0,value:w,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}G++}function i(){if(G--,G===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:V({},e,{value:de}),info:V({},e,{value:Ee}),warn:V({},e,{value:me}),error:V({},e,{value:ve}),group:V({},e,{value:ge}),groupCollapsed:V({},e,{value:be}),groupEnd:V({},e,{value:he})})}0>G&&console.error("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}function m(e){if($===void 0)try{throw Error()}catch(r){var t=r.stack.trim().match(/\n( *(at )?)/);$=t&&t[1]||"",xe=-1<r.stack.indexOf(` at`)?" (<anonymous>)":-1<r.stack.indexOf("@")?"@unknown:0:0":""}return` `+$+e+xe}function a(e,t){if(!e||ee)return"";var r=te.get(e);if(r!==void 0)return r;ee=!0,r=Error.prepareStackTrace,Error.prepareStackTrace=void 0;var c=null;c=z.H,z.H=null,u();try{var R={DetermineComponentFrameRoot:function(){try{if(t){var M=function(){throw Error()};if(Object.defineProperty(M.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(M,[])}catch(k){var J=k}Reflect.construct(e,[],M)}else{try{M.call()}catch(k){J=k}e.call(M.prototype)}}else{try{throw Error()}catch(k){J=k}(M=e())&&typeof M.catch=="function"&&M.catch(function(){})}}catch(k){if(k&&J&&typeof k.stack=="string")return[k.stack,J.stack]}return[null,null]}};R.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var g=Object.getOwnPropertyDescriptor(R.DetermineComponentFrameRoot,"name");g&&g.configurable&&Object.defineProperty(R.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var n=R.DetermineComponentFrameRoot(),N=n[0],U=n[1];if(N&&U){var T=N.split(` `),B=U.split(` `);for(n=g=0;g<T.length&&!T[g].includes("DetermineComponentFrameRoot");)g++;for(;n<B.length&&!B[n].includes("DetermineComponentFrameRoot");)n++;if(g===T.length||n===B.length)for(g=T.length-1,n=B.length-1;1<=g&&0<=n&&T[g]!==B[n];)n--;for(;1<=g&&0<=n;g--,n--)if(T[g]!==B[n]){if(g!==1||n!==1)do if(g--,n--,0>n||T[g]!==B[n]){var H=` `+T[g].replace(" at new "," at ");return e.displayName&&H.includes("<anonymous>")&&(H=H.replace("<anonymous>",e.displayName)),typeof e=="function"&&te.set(e,H),H}while(1<=g&&0<=n);break}}}finally{ee=!1,z.H=c,i(),Error.prepareStackTrace=r}return T=(T=e?e.displayName||e.name:"")?m(T):"",typeof e=="function"&&te.set(e,T),T}function b(e){if(e==null)return"";if(typeof e=="function"){var t=e.prototype;return a(e,!(!t||!t.isReactComponent))}if(typeof e=="string")return m(e);switch(e){case I:return m("Suspense");case Z:return m("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case D:return e=a(e.render,!1),e;case Q:return b(e.type);case K:t=e._payload,e=e._init;try{return b(e(t))}catch{}}return""}function E(){var e=z.A;return e===null?null:e.getOwner()}function d(e){if(fe.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return e.key!==void 0}function s(e,t){function r(){pe||(pe=!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)",t))}r.isReactWarning=!0,Object.defineProperty(e,"key",{get:r,configurable:!0})}function y(){var e=o(this.type);return we[e]||(we[e]=!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.")),e=this.props.ref,e!==void 0?e:null}function A(e,t,r,c,R,g){return r=g.ref,e={$$typeof:f,type:e,key:t,props:g,_owner:R},(r!==void 0?r:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:y}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function j(e,t,r,c,R,g){if(typeof e=="string"||typeof e=="function"||e===Y||e===ue||e===se||e===I||e===Z||e===Oe||typeof e=="object"&&e!==null&&(e.$$typeof===K||e.$$typeof===Q||e.$$typeof===le||e.$$typeof===ce||e.$$typeof===D||e.$$typeof===ke||e.getModuleId!==void 0)){var n=t.children;if(n!==void 0)if(c)if(q(n)){for(c=0;c<n.length;c++)v(n[c],e);Object.freeze&&Object.freeze(n)}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 v(n,e)}else n="",(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(n+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."),e===null?c="null":q(e)?c="array":e!==void 0&&e.$$typeof===f?(c="<"+(o(e.type)||"Unknown")+" />",n=" Did you accidentally export a JSX literal instead of a component?"):c=typeof e,console.error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",c,n);if(fe.call(t,"key")){n=o(e);var N=Object.keys(t).filter(function(T){return T!=="key"});c=0<N.length?"{key: someKey, "+N.join(": ..., ")+": ...}":"{key: someKey}",ye[n+c]||(N=0<N.length?"{"+N.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} />`,c,n,N,n),ye[n+c]=!0)}if(n=null,r!==void 0&&(p(r),n=""+r),d(t)&&(p(t.key),n=""+t.key),"key"in t){r={};for(var U in t)U!=="key"&&(r[U]=t[U])}else r=t;return n&&s(r,typeof e=="function"?e.displayName||e.name||"Unknown":e),A(e,n,g,R,E(),r)}function v(e,t){if(typeof e=="object"&&e&&e.$$typeof!==Pe){if(q(e))for(var r=0;r<e.length;r++){var c=e[r];C(c)&&_(c,t)}else if(C(e))e._store&&(e._store.validated=1);else if(e===null||typeof e!="object"?r=null:(r=ie&&e[ie]||e["@@iterator"],r=typeof r=="function"?r:null),typeof r=="function"&&r!==e.entries&&(r=r.call(e),r!==e))for(;!(e=r.next()).done;)C(e.value)&&_(e.value,t)}}function C(e){return typeof e=="object"&&e!==null&&e.$$typeof===f}function _(e,t){if(e._store&&!e._store.validated&&e.key==null&&(e._store.validated=1,t=S(t),!Ae[t])){Ae[t]=!0;var r="";e&&e._owner!=null&&e._owner!==E()&&(r=null,typeof e._owner.tag=="number"?r=o(e._owner.type):typeof e._owner.name=="string"&&(r=e._owner.name),r=" It was passed a child from "+r+".");var c=z.getCurrentStack;z.getCurrentStack=function(){var R=b(e.type);return c&&(R+=c()||""),R},console.error('Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.',t,r),z.getCurrentStack=c}}function S(e){var t="",r=E();return r&&(r=o(r.type))&&(t=` Check the render method of \``+r+"`."),t||(e=o(e))&&(t=` Check the top-level render call using <`+e+">."),t}var h=x,f=Symbol.for("react.transitional.element"),O=Symbol.for("react.portal"),Y=Symbol.for("react.fragment"),se=Symbol.for("react.strict_mode"),ue=Symbol.for("react.profiler"),ce=Symbol.for("react.consumer"),le=Symbol.for("react.context"),D=Symbol.for("react.forward_ref"),I=Symbol.for("react.suspense"),Z=Symbol.for("react.suspense_list"),Q=Symbol.for("react.memo"),K=Symbol.for("react.lazy"),Oe=Symbol.for("react.offscreen"),ie=Symbol.iterator,Ne=Symbol.for("react.client.reference"),z=h.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,fe=Object.prototype.hasOwnProperty,V=Object.assign,ke=Symbol.for("react.client.reference"),q=Array.isArray,G=0,de,Ee,me,ve,ge,be,he;w.__reactDisabledLog=!0;var $,xe,ee=!1,te=new(typeof WeakMap=="function"?WeakMap:Map),Pe=Symbol.for("react.client.reference"),pe,we={},ye={},Ae={};F.Fragment=Y,F.jsx=function(e,t,r,c,R){return j(e,t,r,!1,c,R)},F.jsxs=function(e,t,r,c,R){return j(e,t,r,!0,c,R)}}()),F}process.env.NODE_ENV==="production"?X.exports=Re():X.exports=Te();var oe=X.exports;const _e=(o,l,p,w)=>{let u=l/(p+w),i=Math.floor(o.length/u);u>o.length&&(u=o.length,i=1);const m=[];for(let a=0;a<u;a++){let b=0;for(let E=0;E<i&&a*i+E<o.length;E++)b+=o[a*i+E];m.push(b/i)}return m},Se=(o,l,p,w,u,i)=>{const m=l.height/2,a=l.getContext("2d");a&&(a.clearRect(0,0,l.width,l.height),u!=="transparent"&&(a.fillStyle=u,a.fillRect(0,0,l.width,l.height)),o.forEach((b,E)=>{a.fillStyle=i;const d=E*(p+w),s=m-b/2,y=p,A=b||1;a.beginPath(),a.roundRect?(a.roundRect(d,s,y,A,50),a.fill()):a.fillRect(d,s,y,A)}))},je=({mediaRecorder:o,width:l="100%",height:p="100%",barWidth:w=2,gap:u=1,backgroundColor:i="transparent",barColor:m="rgb(160, 198, 255)",fftSize:a=1024,maxDecibels:b=-10,minDecibels:E=-90,smoothingTimeConstant:d=.4})=>{const[s,y]=x.useState(),[A,j]=x.useState(),[v,C]=x.useState(),_=x.useRef(null);x.useEffect(()=>{if(!o.stream)return;const f=new AudioContext,O=f.createAnalyser();C(O),O.fftSize=a,O.minDecibels=E,O.maxDecibels=b,O.smoothingTimeConstant=d;const Y=f.createMediaStreamSource(o.stream);return Y.connect(O),y(f),j(Y),()=>{Y.disconnect(),O.disconnect(),f.state!=="closed"&&f.close()}},[o.stream]),x.useEffect(()=>{v&&o.state==="recording"&&S()},[v,o.state]);const S=x.useCallback(()=>{if(!v||!s)return;const f=new Uint8Array(v==null?void 0:v.frequencyBinCount);o.state==="recording"?(v==null||v.getByteFrequencyData(f),h(f),requestAnimationFrame(S)):o.state==="paused"?h(f):o.state==="inactive"&&s.state!=="closed"&&s.close()},[v,s==null?void 0:s.state]);x.useEffect(()=>()=>{s&&s.state!=="closed"&&s.close(),A==null||A.disconnect(),v==null||v.disconnect()},[]);const h=f=>{if(!_.current)return;const O=_e(f,_.current.width,w,u);Se(O,_.current,w,u,i,m)};return oe.jsx("canvas",{ref:_,width:l,height:p,style:{aspectRatio:"unset"}})},Ce=(o,l,p,w,u)=>{const i=o.getChannelData(0),m=p/(w+u),a=Math.floor(i.length/m),b=l/2;let E=[],d=0;for(let s=0;s<m;s++){const y=[];let A=0;const j=[];let v=0;for(let h=0;h<a&&s*a+h<o.length;h++){const f=i[s*a+h];f<=0&&(y.push(f),A++),f>0&&(j.push(f),v++)}const C=y.reduce((h,f)=>h+f,0)/A,S={max:j.reduce((h,f)=>h+f,0)/v,min:C};S.max>d&&(d=S.max),Math.abs(S.min)>d&&(d=Math.abs(S.min)),E.push(S)}if(b*.8>d*b){const s=b*.8/d;E=E.map(y=>({max:y.max*s,min:y.min*s}))}return E},L=(o,l,p,w,u,i,m,a=0,b=1)=>{const E=l.height/2,d=l.getContext("2d");if(!d)return;d.clearRect(0,0,l.width,l.height),u!=="transparent"&&(d.fillStyle=u,d.fillRect(0,0,l.width,l.height));const s=(a||0)/b;o.forEach((y,A)=>{const j=A/o.length,v=s>j;d.fillStyle=v&&m?m:i;const C=A*(p+w),_=E+y.min,S=p,h=E+y.max-_;d.beginPath(),d.roundRect?(d.roundRect(C,_,S,h,50),d.fill()):d.fillRect(C,_,S,h)})},ae=x.forwardRef(({blob:o,width:l,height:p,barWidth:w=2,gap:u=1,currentTime:i,style:m,backgroundColor:a="transparent",barColor:b="rgb(184, 184, 184)",barPlayedColor:E="rgb(160, 198, 255)"},d)=>{const s=x.useRef(null),[y,A]=x.useState([]),[j,v]=x.useState(0);return x.useImperativeHandle(d,()=>s.current,[]),x.useEffect(()=>{(async()=>{if(!s.current)return;if(!o){const h=Array.from({length:100},()=>({max:0,min:0}));L(h,s.current,w,u,a,b,E);return}const _=await o.arrayBuffer();await new AudioContext().decodeAudioData(_,h=>{if(!s.current)return;v(h.duration);const f=Ce(h,p,l,w,u);A(f),L(f,s.current,w,u,a,b,E)})})()},[o,s.current]),x.useEffect(()=>{s.current&&L(y,s.current,w,u,a,b,E,i,j)},[i,j]),oe.jsx("canvas",{ref:s,width:l,height:p,style:{...m}})});ae.displayName="AudioVisualizer",P.AudioVisualizer=ae,P.LiveAudioVisualizer=je,Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})});