From 4d1c3d958be42c43395607f08dc8569ae5a04390 Mon Sep 17 00:00:00 2001 From: Pihkaal Date: Mon, 12 Feb 2024 00:28:27 +0100 Subject: [PATCH] feat(cava): smoothing --- src/components/Music/Cava.tsx | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/components/Music/Cava.tsx b/src/components/Music/Cava.tsx index 3af57c3..c10bef0 100644 --- a/src/components/Music/Cava.tsx +++ b/src/components/Music/Cava.tsx @@ -21,11 +21,13 @@ export const Cava = () => { audioContext.current.createMediaElementSource(audioElement); audioSource.connect(analyser.current); analyser.current.connect(audioContext.current.destination); - audioElement.play(); + void audioElement.play(); + + const analyzerElement = analyser.current; return () => { audioSource.disconnect(); - analyser.current.disconnect(); + analyzerElement.disconnect(); }; }, []); @@ -33,7 +35,7 @@ export const Cava = () => { analyser.current.getByteFrequencyData(dataArray.current); const barCount = Math.floor(width / 3); - const barHeights = []; + const newBarHeights = []; for (let i = 0; i < barCount; i++) { const startIndex = Math.floor((i / barCount) * bufferLength.current); @@ -41,10 +43,22 @@ export const Cava = () => { const slice = dataArray.current.slice(startIndex, endIndex); const sum = slice.reduce((acc, val) => acc + val, 0); const average = sum / slice.length; - barHeights.push(average); + newBarHeights.push(average); } - setBarHeights(barHeights); + const stateBarHeights = + barHeights.length !== newBarHeights.length + ? new Array(newBarHeights.length).fill(0) + : barHeights; + + const smoothedBarHeights = newBarHeights.map((height, i) => { + const smoothingFactor = 0.1; + return ( + stateBarHeights[i] + (height - stateBarHeights[i]) * smoothingFactor + ); + }); + + setBarHeights(smoothedBarHeights); }); return (