Skip to content

Commit

Permalink
Add cleanup. Bump version to 1.2.0 (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
samhirtarif authored Sep 7, 2024
1 parent a0dc505 commit e284411
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"name": "react-audio-visualize",
"private": false,
"version": "1.1.3",
"version": "1.2.0",
"license": "MIT",
"author": "",
"author": "Samhir Tarif",
"repository": {
"type": "git",
"url": "https://github.com/samhirtarif/react-audio-visualize.git"
Expand Down
26 changes: 19 additions & 7 deletions src/LiveAudioVisualizer/LiveAudioVisualizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,21 +89,31 @@ const LiveAudioVisualizer: (props: Props) => ReactElement = ({
minDecibels = -90,
smoothingTimeConstant = 0.4,
}: Props) => {
const [context] = useState(() => new AudioContext());
const [context, setContext] = useState<AudioContext>();
const [audioSource, setAudioSource] = useState<MediaStreamAudioSourceNode>();
const [analyser, setAnalyser] = useState<AnalyserNode>();
const canvasRef = useRef<HTMLCanvasElement>(null);

useEffect(() => {
if (!mediaRecorder.stream) return;

const analyserNode = context.createAnalyser();
const ctx = new AudioContext();
const analyserNode = ctx.createAnalyser();
setAnalyser(analyserNode);
analyserNode.fftSize = fftSize;
analyserNode.minDecibels = minDecibels;
analyserNode.maxDecibels = maxDecibels;
analyserNode.smoothingTimeConstant = smoothingTimeConstant;
const source = context.createMediaStreamSource(mediaRecorder.stream);
const source = ctx.createMediaStreamSource(mediaRecorder.stream);
source.connect(analyserNode);
setContext(ctx);
setAudioSource(source);

return () => {
source.disconnect();
analyserNode.disconnect();
ctx.state !== "closed" && ctx.close();
};
}, [mediaRecorder.stream]);

useEffect(() => {
Expand All @@ -113,7 +123,7 @@ const LiveAudioVisualizer: (props: Props) => ReactElement = ({
}, [analyser, mediaRecorder.state]);

const report = useCallback(() => {
if (!analyser) return;
if (!analyser || !context) return;

const data = new Uint8Array(analyser?.frequencyBinCount);

Expand All @@ -129,14 +139,16 @@ const LiveAudioVisualizer: (props: Props) => ReactElement = ({
) {
context.close();
}
}, [analyser, context.state]);
}, [analyser, context?.state]);

useEffect(() => {
return () => {
if (context.state !== "closed") {
if (context && context.state !== "closed") {
context.close();
}
}
audioSource?.disconnect();
analyser?.disconnect();
};
}, []);

const processFrequencyData = (data: Uint8Array): void => {
Expand Down

0 comments on commit e284411

Please sign in to comment.