fix: sound effects stop music playback in iOS

Co-authored-by: osamu <46447427+sam-osamu@users.noreply.github.com>
This commit is contained in:
naskya 2023-12-04 04:45:51 +00:00 committed by Kainoa Kanter
parent a6aa7d2b74
commit 1011b88850

View file

@ -1,16 +1,25 @@
import { ColdDeviceStorage } from "@/store"; import { ColdDeviceStorage } from "@/store";
const ctx = new AudioContext();
const cache = new Map<string, HTMLAudioElement>(); const cache = new Map<string, HTMLAudioElement>();
export function getAudio(file: string, useCache = true): HTMLAudioElement { export async function getAudio(
let audio: HTMLAudioElement; file: string,
useCache = true,
): HTMLAudioElement {
if (useCache && cache.has(file)) { if (useCache && cache.has(file)) {
audio = cache.get(file); return cache.get(file);
} else {
audio = new Audio(`/static-assets/sounds/${file}.mp3`);
if (useCache) cache.set(file, audio);
} }
return audio;
const response = await fetch(`/static-assets/sounds/${file}.mp3`);
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await ctx.decodeAudioData(arrayBuffer);
if (useCache) {
cache.set(file, audioBuffer);
}
return audioBuffer;
} }
export function setVolume( export function setVolume(
@ -28,11 +37,17 @@ export function play(type: string) {
playFile(sound.type, sound.volume); playFile(sound.type, sound.volume);
} }
export function playFile(file: string, volume: number) { export async function playFile(file: string, volume: number) {
const masterVolume = ColdDeviceStorage.get("sound_masterVolume"); const masterVolume = ColdDeviceStorage.get("sound_masterVolume");
if (masterVolume === 0 || volume === 0 || file.toLowerCase().includes("none")) if (masterVolume === 0 || volume === 0) {
return; return;
}
const audio = setVolume(getAudio(file), volume); const gainNode = ctx.createGain();
audio.play(); gainNode.gain.value = masterVolume * volume;
const soundSource = ctx.createBufferSource();
soundSource.buffer = await getAudio(file);
soundSource.connect(gainNode).connect(ctx.destination);
soundSource.start();
} }