fix: reuse AudioContext

This change fixes an issue where audio is sometimes prevented from playing.

code generated by ChatGPT
This commit is contained in:
Guanran Wang 2024-11-23 02:32:55 +08:00
parent 6577ce16f8
commit 13c0e8d779
Signed by: nyancat
GPG key ID: 91F97D9ED12639CF

View file

@ -7,21 +7,24 @@ type Button = {
};
const audioCache: Record<string, AudioBuffer> = {};
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();
};