hippofish/packages/client/src/scripts/sound.ts
naskya 1011b88850 fix: sound effects stop music playback in iOS
Co-authored-by: osamu <46447427+sam-osamu@users.noreply.github.com>
2023-12-04 04:45:51 +00:00

53 lines
1.4 KiB
TypeScript

import { ColdDeviceStorage } from "@/store";
const ctx = new AudioContext();
const cache = new Map<string, HTMLAudioElement>();
export async function getAudio(
file: string,
useCache = true,
): HTMLAudioElement {
if (useCache && cache.has(file)) {
return cache.get(file);
}
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(
audio: HTMLAudioElement,
volume: number,
): HTMLAudioElement {
const masterVolume = ColdDeviceStorage.get("sound_masterVolume");
audio.volume = masterVolume - (1 - volume) * masterVolume;
return audio;
}
export function play(type: string) {
const sound = ColdDeviceStorage.get(`sound_${type}` as any);
if (sound.type == null) return;
playFile(sound.type, sound.volume);
}
export async function playFile(file: string, volume: number) {
const masterVolume = ColdDeviceStorage.get("sound_masterVolume");
if (masterVolume === 0 || volume === 0) {
return;
}
const gainNode = ctx.createGain();
gainNode.gain.value = masterVolume * volume;
const soundSource = ctx.createBufferSource();
soundSource.buffer = await getAudio(file);
soundSource.connect(gainNode).connect(ctx.destination);
soundSource.start();
}