Skip to content

Fix memory leak in AudioLevelIndicator #703

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 21, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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