From f629ad327dc5926270a30c9e202cc4ebb0908b5b Mon Sep 17 00:00:00 2001 From: naskya <m@naskya.net> Date: Sun, 16 Jun 2024 23:10:50 +0900 Subject: [PATCH] fix (client): client crashes when Web Audio API is disabled (close #10948) --- packages/client/src/scripts/sound.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/client/src/scripts/sound.ts b/packages/client/src/scripts/sound.ts index 289eb9e0b3..76e972b896 100644 --- a/packages/client/src/scripts/sound.ts +++ b/packages/client/src/scripts/sound.ts @@ -1,14 +1,23 @@ import { ColdDeviceStorage } from "@/store"; -const ctx = new AudioContext(); -const cache = new Map<string, HTMLAudioElement>(); +let ctx: AudioContext | null; +try { + ctx = new AudioContext(); +} catch { + ctx = null; +} + +const cache = new Map<string, AudioBuffer>(); export async function getAudio( file: string, useCache = true, -): HTMLAudioElement { +): Promise<AudioBuffer | null> { if (useCache && cache.has(file)) { - return cache.get(file); + return cache.get(file) ?? null; + } + if (ctx == null) { + return null; } const response = await fetch(`/static-assets/sounds/${file}.mp3`); @@ -39,7 +48,7 @@ export function play(type: string) { export async function playFile(file: string, volume: number) { const masterVolume = ColdDeviceStorage.get("sound_masterVolume"); - if (masterVolume === 0 || volume === 0) { + if (ctx == null || masterVolume === 0 || volume === 0) { return; }