Skip to content
This repository was archived by the owner on May 3, 2025. It is now read-only.

Commit f3f8c77

Browse files
Add effect for unmounting + disposing of Tone track data (channels, samplers and sequences) to prevent changes from leaking into main project (#113)
1 parent 70e28b3 commit f3f8c77

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/utils/hooks/use-tone-audio.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import MediaRecorder, {
2727
import OpusMediaRecorder from "opus-media-recorder";
2828
import { toaster } from "evergreen-ui";
2929
import { env } from "utils/env";
30+
import { useWillUnmount } from "rooks";
3031

3132
interface UseToneAudioOptions
3233
extends Pick<ToneState, "isPlaying" | "isRecording" | "subdivision">,
@@ -247,17 +248,32 @@ const useToneAudio = (options: UseToneAudioOptions): UseToneAudioResult => {
247248
updateTracks({ isPlaying: false, loop: true }, toneTracksRef.current);
248249
}, [isRecording, lengthInMs, mimeType, onRecordingComplete]);
249250

251+
useWillUnmount(() => {
252+
cleanupTracks(toneTracksRef.current);
253+
toneTracksRef.current = Map();
254+
Tone.Transport.stop();
255+
});
256+
250257
const isLoading = loadingState.some((loading) => loading);
251258

252259
return {
253260
isLoading,
254261
};
255262
};
256263

264+
const cleanupTracks = (tracks: Map<string, ToneTrack>): void => {
265+
tracks.forEach((toneTrack) => {
266+
const { channel, sampler, sequence } = toneTrack;
267+
channel.dispose();
268+
sampler.dispose();
269+
sequence.dispose();
270+
});
271+
};
272+
257273
const updateTracks = (
258274
options: Pick<UseToneAudioOptions, "loop" | "isPlaying">,
259275
tracks: Map<string, ToneTrack>
260-
) => {
276+
): void => {
261277
const { loop, isPlaying } = options;
262278
tracks.forEach((toneTrack) => {
263279
if (loop != null) {

0 commit comments

Comments
 (0)