From 72eada287370dd5cdb1a2d2d0077d74d9ac8972e Mon Sep 17 00:00:00 2001 From: Guanran Wang Date: Sun, 17 Nov 2024 17:55:45 +0800 Subject: [PATCH] chore: cache audio file code generated by ChatGPT --- src/main.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main.ts b/src/main.ts index 006b594..ef0f981 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,11 +1,18 @@ +const audioCache: Record = {}; + const audioPlay = async (url: string) => { + if (!audioCache[url]) { + const context = new AudioContext(); + const audioBuffer = await fetch(url) + .then((res) => res.arrayBuffer()) + .then((arrayBuffer) => context.decodeAudioData(arrayBuffer)); + + audioCache[url] = audioBuffer; + } + const context = new AudioContext(); const source = context.createBufferSource(); - const audioBuffer = await fetch(url) - .then((res) => res.arrayBuffer()) - .then((ArrayBuffer) => context.decodeAudioData(ArrayBuffer)); - - source.buffer = audioBuffer; + source.buffer = audioCache[url]; source.connect(context.destination); source.start(); };