fix: reuse AudioContext
This change fixes an issue where audio is sometimes prevented from playing. code generated by ChatGPT
This commit is contained in:
parent
6577ce16f8
commit
13c0e8d779
1 changed files with 8 additions and 5 deletions
13
src/main.ts
13
src/main.ts
|
@ -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();
|
||||
};
|
||||
|
||||
|
|
Loading…
Reference in a new issue