laif-ds
Version:
Design System di Laif con componenti React basati su principi di Atomic Design
96 lines (95 loc) • 2.92 kB
JavaScript
"use client";
import { jsx as g } from "react/jsx-runtime";
import { useRef as i, useEffect as w } from "react";
const c = {
FFT_SIZE: 512,
SMOOTHING: 0.8,
MIN_BAR_HEIGHT: 2,
MIN_BAR_WIDTH: 2,
BAR_SPACING: 1,
COLOR: {
MIN_INTENSITY: 100,
// Minimum gray value (darker)
MAX_INTENSITY: 255,
// Maximum gray value (brighter)
INTENSITY_RANGE: 155
// MAX_INTENSITY - MIN_INTENSITY
}
};
function x({
stream: u,
isRecording: l,
onClick: S
}) {
const a = i(null), d = i(null), f = i(null), I = i(null), h = i(null), R = () => {
I.current && cancelAnimationFrame(I.current), d.current && d.current.close();
};
w(() => R, []), w(() => {
u && l ? C() : R();
}, [u, l]), w(() => {
const e = () => {
if (typeof window > "u" || !a.current || !h.current)
return;
const t = h.current, n = a.current, o = window.devicePixelRatio || 1, r = t.getBoundingClientRect();
n.width = (r.width - 2) * o, n.height = (r.height - 2) * o, n.style.width = `${r.width - 2}px`, n.style.height = `${r.height - 2}px`;
};
if (typeof window < "u")
return window.addEventListener("resize", e), e(), () => window.removeEventListener("resize", e);
}, []);
const C = async () => {
try {
const e = new AudioContext();
d.current = e;
const t = e.createAnalyser();
t.fftSize = c.FFT_SIZE, t.smoothingTimeConstant = c.SMOOTHING, f.current = t, e.createMediaStreamSource(u).connect(t), p();
} catch (e) {
console.error("Error starting visualization:", e);
}
}, E = (e) => {
const t = Math.floor(e * c.COLOR.INTENSITY_RANGE) + c.COLOR.MIN_INTENSITY;
return `rgb(${t}, ${t}, ${t})`;
}, M = (e, t, n, o, r, s) => {
e.fillStyle = s, e.fillRect(t, n - r, o, r), e.fillRect(t, n, o, r);
}, p = () => {
if (!l) return;
const e = a.current, t = e?.getContext("2d");
if (!e || !t || !f.current) return;
const n = window.devicePixelRatio || 1;
t.scale(n, n);
const o = f.current, r = o.frequencyBinCount, s = new Uint8Array(r), A = () => {
I.current = requestAnimationFrame(A), o.getByteFrequencyData(s), t.clearRect(0, 0, e.width / n, e.height / n);
const T = Math.max(
c.MIN_BAR_WIDTH,
e.width / n / r - c.BAR_SPACING
), _ = e.height / n / 2;
let m = 0;
for (let N = 0; N < r; N++) {
const y = s[N] / 255, B = Math.max(
c.MIN_BAR_HEIGHT,
y * _
);
M(
t,
m,
_,
T,
B,
E(y)
), m += T + c.BAR_SPACING;
}
};
A();
};
return /* @__PURE__ */ g(
"div",
{
ref: h,
className: "bg-d-background/80 h-full w-full cursor-pointer rounded-lg backdrop-blur",
onClick: S,
children: /* @__PURE__ */ g("canvas", { ref: a, className: "h-full w-full" })
}
);
}
export {
x as AudioVisualizer
};