hippofish/packages/client/src/scripts/sound.ts

54 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-01-13 05:40:33 +01:00
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;
}
2023-01-13 05:40:33 +01:00
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) {
2023-01-16 20:19:20 +01:00
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) {
2023-01-13 05:40:33 +01:00
const masterVolume = ColdDeviceStorage.get("sound_masterVolume");
if (masterVolume === 0 || volume === 0) {
2023-04-02 06:10:31 +02:00
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();
}