main init
This commit is contained in:
196
Library/mobile/kit/audio.ts
Normal file
196
Library/mobile/kit/audio.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
// Kit audio (v1) - WebAudio music + SFX for Vite/Capacitor apps. From _Tools\Library\mobile\kit.
|
||||
// Generalised from XP-Battleship/src/audio.ts. Everything is best effort: missing files or a
|
||||
// locked AudioContext never throw.
|
||||
//
|
||||
// configureAudio({ base: "/assets/audio/", storageKey: "mygame", preload: ["sfx_click"],
|
||||
// throttle: { sfx_laser: 90 } });
|
||||
// initAudio(); // from the first user gesture (autoplay policy)
|
||||
// playMusic("music_game"); playSfx("sfx_click", 0.8); toggleMute(); setVolumes(0.35, 1);
|
||||
|
||||
interface AudioConfig {
|
||||
base: string;
|
||||
ext: string;
|
||||
storageKey: string;
|
||||
preload: string[];
|
||||
throttle: Record<string, number>;
|
||||
}
|
||||
|
||||
const cfg: AudioConfig = { base: "/assets/audio/", ext: ".mp3", storageKey: "app", preload: [], throttle: {} };
|
||||
|
||||
let ctx: AudioContext | null = null;
|
||||
let musicGain: GainNode | null = null;
|
||||
let sfxGain: GainNode | null = null;
|
||||
let musicSource: AudioBufferSourceNode | null = null;
|
||||
let currentMusic: string | null = null;
|
||||
let muted = false;
|
||||
let musicVol = 0.35;
|
||||
let sfxVol = 1;
|
||||
|
||||
const buffers = new Map<string, AudioBuffer>();
|
||||
const loading = new Map<string, Promise<AudioBuffer | null>>();
|
||||
const lastPlayed = new Map<string, number>();
|
||||
|
||||
function muteKey(): string {
|
||||
return `${cfg.storageKey}_muted`;
|
||||
}
|
||||
|
||||
export function configureAudio(c: Partial<AudioConfig>): void {
|
||||
Object.assign(cfg, c);
|
||||
try {
|
||||
muted = localStorage.getItem(muteKey()) === "1";
|
||||
} catch {
|
||||
muted = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Suspend while hidden, resume on return - Android otherwise leaves the context suspended
|
||||
// after backgrounding, silencing the game for good.
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!ctx) return;
|
||||
if (document.hidden) void ctx.suspend().catch(() => {});
|
||||
else void ctx.resume().catch(() => {});
|
||||
});
|
||||
|
||||
function loadBuffer(name: string): Promise<AudioBuffer | null> {
|
||||
if (!ctx) return Promise.resolve(null);
|
||||
const done = buffers.get(name);
|
||||
if (done) return Promise.resolve(done);
|
||||
const inflight = loading.get(name); // parallel callers share one fetch
|
||||
if (inflight) return inflight;
|
||||
const p = (async (): Promise<AudioBuffer | null> => {
|
||||
try {
|
||||
const res = await fetch(`${cfg.base}${name}${cfg.ext}`);
|
||||
if (!res.ok) return null;
|
||||
const buf = await ctx!.decodeAudioData(await res.arrayBuffer());
|
||||
buffers.set(name, buf);
|
||||
return buf;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
loading.delete(name);
|
||||
}
|
||||
})();
|
||||
loading.set(name, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Call from a user gesture. Safe to call repeatedly. */
|
||||
export function initAudio(): void {
|
||||
if (ctx) {
|
||||
void ctx.resume().catch(() => {});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ctx = new AudioContext();
|
||||
musicGain = ctx.createGain();
|
||||
musicGain.gain.value = muted ? 0 : musicVol;
|
||||
musicGain.connect(ctx.destination);
|
||||
sfxGain = ctx.createGain();
|
||||
sfxGain.gain.value = muted ? 0 : sfxVol;
|
||||
sfxGain.connect(ctx.destination);
|
||||
for (const n of cfg.preload) void loadBuffer(n);
|
||||
} catch {
|
||||
ctx = null;
|
||||
}
|
||||
}
|
||||
|
||||
export function playMusic(name: string): void {
|
||||
if (!ctx || !musicGain || currentMusic === name) return;
|
||||
currentMusic = name;
|
||||
void ctx.resume().catch(() => {});
|
||||
void loadBuffer(name).then((buf) => {
|
||||
if (!ctx || !musicGain || currentMusic !== name) return; // another track requested meanwhile
|
||||
if (!buf) {
|
||||
currentMusic = null; // allow a retry later
|
||||
return;
|
||||
}
|
||||
musicSource?.stop();
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf;
|
||||
src.loop = true;
|
||||
src.connect(musicGain);
|
||||
src.start();
|
||||
musicSource = src;
|
||||
});
|
||||
}
|
||||
|
||||
export function stopMusic(): void {
|
||||
currentMusic = null;
|
||||
musicSource?.stop();
|
||||
musicSource = null;
|
||||
}
|
||||
|
||||
export function playSfx(name: string, volume = 1): void {
|
||||
if (!ctx || !sfxGain || muted) return;
|
||||
// mobile browsers suspend the context between plays far more readily than desktop
|
||||
void ctx.resume().catch(() => {});
|
||||
const gap = cfg.throttle[name] ?? 0;
|
||||
const now = performance.now();
|
||||
if (gap && now - (lastPlayed.get(name) ?? 0) < gap) return;
|
||||
lastPlayed.set(name, now);
|
||||
const buf = buffers.get(name);
|
||||
if (buf) {
|
||||
playBuffer(buf, volume);
|
||||
return;
|
||||
}
|
||||
// not preloaded: decode once, THEN play - otherwise the first use of a rare clip is silent
|
||||
void loadBuffer(name).then((decoded) => {
|
||||
if (decoded && ctx && sfxGain && !muted) playBuffer(decoded, volume);
|
||||
});
|
||||
}
|
||||
|
||||
function playBuffer(buf: AudioBuffer, volume: number): void {
|
||||
if (!ctx || !sfxGain) return;
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf;
|
||||
const g = ctx.createGain();
|
||||
g.gain.value = volume;
|
||||
src.connect(g);
|
||||
g.connect(sfxGain);
|
||||
src.start();
|
||||
}
|
||||
|
||||
/** Hard pause (rewarded ad showing, app hidden). */
|
||||
export function suspendAudio(): void {
|
||||
if (ctx) void ctx.suspend().catch(() => {});
|
||||
}
|
||||
|
||||
export function resumeAudio(): void {
|
||||
if (ctx && !document.hidden) void ctx.resume().catch(() => {});
|
||||
}
|
||||
|
||||
export function isMuted(): boolean {
|
||||
return muted;
|
||||
}
|
||||
|
||||
export function toggleMute(): boolean {
|
||||
muted = !muted;
|
||||
try {
|
||||
localStorage.setItem(muteKey(), muted ? "1" : "0");
|
||||
} catch {
|
||||
// storage unavailable - setting lasts for this session only
|
||||
}
|
||||
applyGains();
|
||||
return muted;
|
||||
}
|
||||
|
||||
export function setVolumes(music: number, sfx: number): void {
|
||||
musicVol = music;
|
||||
sfxVol = sfx;
|
||||
applyGains();
|
||||
}
|
||||
|
||||
function applyGains(): void {
|
||||
if (musicGain) musicGain.gain.value = muted ? 0 : musicVol;
|
||||
if (sfxGain) sfxGain.gain.value = muted ? 0 : sfxVol;
|
||||
}
|
||||
|
||||
/** Fade music out under a big moment; unduck targets the CURRENT volume/mute state. */
|
||||
export function duckMusic(on: boolean): void {
|
||||
if (!ctx || !musicGain) return;
|
||||
void ctx.resume().catch(() => {});
|
||||
const now = ctx.currentTime;
|
||||
musicGain.gain.cancelScheduledValues(now);
|
||||
musicGain.gain.setValueAtTime(musicGain.gain.value, now);
|
||||
musicGain.gain.linearRampToValueAtTime(on ? 0 : muted ? 0 : musicVol, now + (on ? 0.15 : 0.3));
|
||||
}
|
||||
Reference in New Issue
Block a user