review audio data loading

This commit is contained in:
Timo K.
2026-10-02 11:46:40 +02:00
parent d96d00b64a
commit cbe195d449
2 changed files with 6 additions and 7 deletions
+2 -2
View File
@@ -43,12 +43,12 @@ describe("prefetchSounds", () => {
expect(bytesOf(sounds.beep)).toEqual([0x4f, 0x67, 0x67, 0x53]); expect(bytesOf(sounds.beep)).toEqual([0x4f, 0x67, 0x67, 0x53]);
}); });
it("decodes percent-encoded data: URLs without fetching them", async () => { it("leaves out a sound with a percent-encoded data: URL", async () => {
const sounds = await prefetchSounds({ const sounds = await prefetchSounds({
beep: { ogg: "data:audio/ogg,Ogg%53" }, beep: { ogg: "data:audio/ogg,Ogg%53" },
}); });
expect(fetchSpy).not.toHaveBeenCalled(); expect(fetchSpy).not.toHaveBeenCalled();
expect(bytesOf(sounds.beep)).toEqual([0x4f, 0x67, 0x67, 0x53]); expect(sounds).toEqual({});
}); });
it("leaves out a sound whose response is not okay", async () => { it("leaves out a sound whose response is not okay", async () => {
+4 -5
View File
@@ -48,11 +48,11 @@ function decodeDataUrl(url: string): ArrayBuffer {
if (!url.startsWith("data:") || separator === -1) if (!url.startsWith("data:") || separator === -1)
throw new Error("Not a valid data: URL"); throw new Error("Not a valid data: URL");
const header = url.slice("data:".length, separator); const header = url.slice("data:".length, separator);
const payload = url.slice(separator + 1); // Vite only percent-encodes SVGs; every other inlined asset is base64.
const decoded = header.split(";").includes("base64") if (!header.split(";").includes("base64"))
? atob(payload) throw new Error("Only base64 data: URLs are supported");
: decodeURIComponent(payload);
// `decoded` is a binary string: one char per byte // `decoded` is a binary string: one char per byte
const decoded = atob(url.slice(separator + 1));
const bytes = Uint8Array.from(decoded, (c) => c.charCodeAt(0)); const bytes = Uint8Array.from(decoded, (c) => c.charCodeAt(0));
return bytes.buffer; return bytes.buffer;
} }
@@ -90,7 +90,6 @@ export async function prefetchSounds<S extends string>(
buffer = await loadSound(url); buffer = await loadSound(url);
} catch (e) { } catch (e) {
logger.warn(`Could not load sound ${name}`, e); logger.warn(`Could not load sound ${name}`, e);
return;
} }
if (buffer === null) { if (buffer === null) {
// If the sound doesn't load, it's not the end of the world. We won't play // If the sound doesn't load, it's not the end of the world. We won't play