From 13c0e8d779d7d8319e2e6868f11d7b19b4b2bcb6 Mon Sep 17 00:00:00 2001 From: Guanran Wang Date: Sat, 23 Nov 2024 02:32:55 +0800 Subject: [PATCH] fix: reuse AudioContext This change fixes an issue where audio is sometimes prevented from playing. code generated by ChatGPT --- src/main.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main.ts b/src/main.ts index 02d2e74..d493d96 100644 --- a/src/main.ts +++ b/src/main.ts @@ -7,21 +7,24 @@ type Button = { }; const audioCache: Record = {}; +const audioContext = new AudioContext(); const audioPlay = async (url: string) => { + if (audioContext.state === "suspended") { + await audioContext.resume(); + } + if (!audioCache[url]) { - const context = new AudioContext(); const audioBuffer = await fetch(url) .then((res) => res.arrayBuffer()) - .then((arrayBuffer) => context.decodeAudioData(arrayBuffer)); + .then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer)); audioCache[url] = audioBuffer; } - const context = new AudioContext(); - const source = context.createBufferSource(); + const source = audioContext.createBufferSource(); source.buffer = audioCache[url]; - source.connect(context.destination); + source.connect(audioContext.destination); source.start(); };