diff --git a/ts/components/GlobalAudioContext.tsx b/ts/components/GlobalAudioContext.tsx index e2bcaf125..a1208f263 100644 --- a/ts/components/GlobalAudioContext.tsx +++ b/ts/components/GlobalAudioContext.tsx @@ -26,8 +26,7 @@ export type Contents = { // and instantiate these inside of `GlobalAudioProvider`. (We may wish to keep // `audioContext` global, however, as the browser limits the number that can be // created.) -const audioContext = new AudioContext(); -void audioContext.suspend(); +let audioContext: AudioContext | undefined; const waveformCache: WaveformCache = new LRU({ max: MAX_WAVEFORM_COUNT, @@ -106,6 +105,11 @@ async function doComputePeaks( return emptyResult; } + if (!audioContext) { + audioContext = new AudioContext(); + await audioContext.suspend(); + } + const data = await audioContext.decodeAudioData(raw); // Compute RMS peaks diff --git a/ts/util/Sound.ts b/ts/util/Sound.ts index 8be109a65..65ada0cfd 100644 --- a/ts/util/Sound.ts +++ b/ts/util/Sound.ts @@ -11,7 +11,7 @@ export type SoundOpts = { export class Sound { static sounds = new Map(); - private readonly context = new AudioContext(); + private static context: AudioContext | undefined; private readonly loop: boolean; @@ -59,6 +59,13 @@ export class Sound { } } + private get context(): AudioContext { + if (!Sound.context) { + Sound.context = new AudioContext(); + } + return Sound.context; + } + static async loadSoundFile(src: string): Promise { const xhr = new XMLHttpRequest();