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 audioCache: Record<string, AudioBuffer> = {};
|
||||||
|
const audioContext = new AudioContext();
|
||||||
|
|
||||||
const audioPlay = async (url: string) => {
|
const audioPlay = async (url: string) => {
|
||||||
|
if (audioContext.state === "suspended") {
|
||||||
|
await audioContext.resume();
|
||||||
|
}
|
||||||
|
|
||||||
if (!audioCache[url]) {
|
if (!audioCache[url]) {
|
||||||
const context = new AudioContext();
|
|
||||||
const audioBuffer = await fetch(url)
|
const audioBuffer = await fetch(url)
|
||||||
.then((res) => res.arrayBuffer())
|
.then((res) => res.arrayBuffer())
|
||||||
.then((arrayBuffer) => context.decodeAudioData(arrayBuffer));
|
.then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer));
|
||||||
|
|
||||||
audioCache[url] = audioBuffer;
|
audioCache[url] = audioBuffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
const context = new AudioContext();
|
const source = audioContext.createBufferSource();
|
||||||
const source = context.createBufferSource();
|
|
||||||
source.buffer = audioCache[url];
|
source.buffer = audioCache[url];
|
||||||
source.connect(context.destination);
|
source.connect(audioContext.destination);
|
||||||
source.start();
|
source.start();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue