Skip to content

Commit

Permalink
Fix memory leak in AudioLevelIndicator (#703)
Browse files Browse the repository at this point in the history
* Fix memory leak in AudioLevelIndicator

* Prevent context from being closed twice

* Spacing
  • Loading branch information
timmydoza committed Jun 21, 2022
1 parent f91bab9 commit d4c418c
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/components/AudioLevelIndicator/AudioLevelIndicator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,25 @@ const getUniqueClipId = () => clipId++;

// @ts-ignore
const AudioContext = window.AudioContext || window.webkitAudioContext;
let audioContext: AudioContext;

export function initializeAnalyser(stream: MediaStream) {
audioContext = audioContext || new AudioContext();
const audioContext = new AudioContext(); // Create a new audioContext for each audio indicator
const audioSource = audioContext.createMediaStreamSource(stream);

const analyser = audioContext.createAnalyser();
analyser.smoothingTimeConstant = 0.2;
analyser.fftSize = 256;

audioSource.connect(analyser);

// Here we provide a way for the audioContext to be closed.
// Closing the audioContext allows the unused audioSource to be garbage collected.
stream.addEventListener('cleanup', () => {
if (audioContext.state !== 'closed') {
audioContext.close();
}
});

return analyser;
}

Expand All @@ -40,7 +48,10 @@ function AudioLevelIndicator({ audioTrack, color = 'white' }: { audioTrack?: Aud
// we stop the cloned track that is stored in 'newMediaStream'. It is important that we stop
// all tracks when they are not in use. Browsers like Firefox don't let you create a new stream
// from a new audio device while the active audio device still has active tracks.
const stopAllMediaStreamTracks = () => newMediaStream.getTracks().forEach(track => track.stop());
const stopAllMediaStreamTracks = () => {
newMediaStream.getTracks().forEach(track => track.stop());
newMediaStream.dispatchEvent(new Event('cleanup')); // Stop the audioContext
};
audioTrack.on('stopped', stopAllMediaStreamTracks);

const reinitializeAnalyser = () => {
Expand Down

0 comments on commit d4c418c

Please sign in to comment.