Files
_Tools/Library/web/kit/kit-audio.js

158 lines
7.5 KiB
JavaScript
Raw Permalink Normal View History

2026-11-13 00:38:47 +01:00
/* Kit audio (v1) - WebAudio for HTML games. From _Tools\Library\web\kit. Needs kit-core.js.
const audio = Kit.createAudio({
prefix: 'mygame', // localStorage keys mygame.muted / .music / .sfx
dir: 'assets/Audio/', ext: '.mp3', // where ComfyGen adopt_audio puts the files
files: ['sfx_click', 'sfx_win', 'music_game'],
throttle: { sfx_step: 60 }, // optional min gap in ms per clip
});
audio.sfx('sfx_click') play once (silent if missing / not decoded yet)
audio.music('music_game') loop as music (switching tracks fades the old one)
const h = audio.loop('sfx_flow', 0.5); h.stop() looping effect
audio.tone(880, 0.1) / audio.noise(0.2) synth fallback sounds, no files needed
audio.toggleMute() / audio.setVolume(music, sfx) / audio.muted / audio.musicVol / audio.sfxVol
Best effort everywhere: missing files, a blocked AudioContext or no WebAudio never throw.
The context is created on the first pointer/key press (autoplay policy) - nothing to call. */
(function (root) {
'use strict';
const Kit = (root.Kit = root.Kit || {});
Kit.createAudio = (opt = {}) => {
const st = Kit.store(opt.prefix || 'kit');
const dir = opt.dir || 'assets/Audio/', ext = opt.ext || '.mp3';
const files = opt.files || [], throttle = opt.throttle || {};
let ctx = null, musicGain = null, sfxGain = null, musicSrc = null, musicName = null, wantMusic = null;
const buffers = {}, loading = {}, last = {};
const api = {
muted: st.get('muted', false),
musicVol: st.get('music', 0.35),
sfxVol: st.get('sfx', 0.8),
};
// slider 0..1 -> gain; squared so the low end of a slider is fine-grained
const g = v => (api.muted ? 0 : v * v);
function unlock() {
if (ctx) { if (ctx.state === 'suspended') ctx.resume().catch(() => {}); return; }
try {
ctx = new (root.AudioContext || root.webkitAudioContext)();
musicGain = ctx.createGain(); musicGain.gain.value = g(api.musicVol); musicGain.connect(ctx.destination);
sfxGain = ctx.createGain(); sfxGain.gain.value = g(api.sfxVol); sfxGain.connect(ctx.destination);
for (const n of files) load(n);
if (wantMusic) api.music(wantMusic);
} catch (e) { ctx = null; }
}
if (typeof document !== 'undefined') {
for (const ev of ['pointerdown', 'keydown', 'touchstart']) addEventListener(ev, unlock, { capture: true, passive: true });
// Android leaves a context suspended after backgrounding unless it is resumed by hand
document.addEventListener('visibilitychange', () => {
if (!ctx) return;
if (document.hidden) ctx.suspend().catch(() => {}); else ctx.resume().catch(() => {});
});
}
function load(name) {
if (!ctx) return Promise.resolve(null);
if (buffers[name]) return Promise.resolve(buffers[name]);
if (loading[name]) return loading[name];
return (loading[name] = Kit.loadBytes(Kit.asset(dir + name + ext))
.then(b => ctx.decodeAudioData(b))
.then(buf => (buffers[name] = buf))
.catch(() => null)
.finally(() => { delete loading[name]; }));
}
function start(buf, vol, loop, bus) {
const src = ctx.createBufferSource();
src.buffer = buf; src.loop = loop;
const gn = ctx.createGain(); gn.gain.value = vol;
src.connect(gn).connect(bus);
src.start();
src.gainNode = gn;
return src;
}
function fadeStop(src) {
if (!src || !ctx) return;
try { src.gainNode.gain.setTargetAtTime(0, ctx.currentTime, 0.08); src.stop(ctx.currentTime + 0.4); } catch (e) { /* stopped */ }
}
api.sfx = (name, vol = 1) => {
if (!ctx || api.muted) return;
if (ctx.state === 'suspended') ctx.resume().catch(() => {});
const gap = throttle[name] || 0, now = performance.now();
if (gap && now - (last[name] || 0) < gap) return;
last[name] = now;
// first use of a clip that is still decoding: play it once it is ready instead of dropping it
if (buffers[name]) start(buffers[name], vol, false, sfxGain);
else load(name).then(b => { if (b && !api.muted) start(b, vol, false, sfxGain); });
};
api.loop = (name, vol = 1) => {
const h = { src: null, stopped: false, stop() { h.stopped = true; fadeStop(h.src); h.src = null; } };
if (!ctx) return h;
load(name).then(b => { if (b && !h.stopped) h.src = start(b, vol, true, sfxGain); });
return h;
};
api.music = name => {
wantMusic = name;
if (!ctx || musicName === name) return;
musicName = name;
load(name).then(b => {
if (!b || musicName !== name) { if (!b && musicName === name) musicName = null; return; }
fadeStop(musicSrc);
musicSrc = start(b, 1, true, musicGain);
});
};
api.stopMusic = () => { wantMusic = null; musicName = null; fadeStop(musicSrc); musicSrc = null; };
function apply() {
if (musicGain) musicGain.gain.value = g(api.musicVol);
if (sfxGain) sfxGain.gain.value = g(api.sfxVol);
}
api.toggleMute = () => { api.muted = !api.muted; st.set('muted', api.muted); apply(); return api.muted; };
api.setVolume = (music, sfx) => {
if (music != null) { api.musicVol = Kit.clamp(+music || 0, 0, 1); st.set('music', api.musicVol); }
if (sfx != null) { api.sfxVol = Kit.clamp(+sfx || 0, 0, 1); st.set('sfx', api.sfxVol); }
if (api.muted && (music > 0 || sfx > 0)) { api.muted = false; st.set('muted', false); }
apply();
};
// duck music under a big moment (ramped, no clicks)
api.duck = (on, secs = 0.2) => {
if (!ctx || !musicGain) return;
const t = ctx.currentTime;
musicGain.gain.cancelScheduledValues(t);
musicGain.gain.setValueAtTime(musicGain.gain.value, t);
musicGain.gain.linearRampToValueAtTime(on ? 0 : g(api.musicVol), t + secs);
};
api.suspend = () => { if (ctx) ctx.suspend().catch(() => {}); };
api.resume = () => { if (ctx && !document.hidden) ctx.resume().catch(() => {}); };
api.unlock = unlock;
// ---- synth (placeholder sounds until ComfyGen clips exist) --------------------------
api.tone = (freq, dur = 0.1, type = 'square', vol = 0.3, slide = 0, delay = 0) => {
if (!ctx || api.muted) return;
const t = ctx.currentTime + delay;
const o = ctx.createOscillator(), gn = ctx.createGain();
o.type = type; o.frequency.setValueAtTime(freq, t);
if (slide) o.frequency.exponentialRampToValueAtTime(Math.max(30, freq + slide), t + dur);
gn.gain.setValueAtTime(vol, t); gn.gain.exponentialRampToValueAtTime(0.001, t + dur);
o.connect(gn).connect(sfxGain); o.start(t); o.stop(t + dur + 0.02);
};
api.noise = (dur = 0.2, vol = 0.3, cutoff = 1200, delay = 0) => {
if (!ctx || api.muted) return;
const t = ctx.currentTime + delay, len = Math.floor(ctx.sampleRate * dur);
const buf = ctx.createBuffer(1, len, ctx.sampleRate), d = buf.getChannelData(0);
for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / len);
const src = ctx.createBufferSource(), f = ctx.createBiquadFilter(), gn = ctx.createGain();
src.buffer = buf; f.type = 'lowpass'; f.frequency.value = cutoff; gn.gain.value = vol;
src.connect(f).connect(gn).connect(sfxGain); src.start(t);
};
// little arpeggio: audio.arp([523, 659, 784], 0.12)
api.arp = (freqs, step = 0.08, type = 'square', vol = 0.18) =>
freqs.forEach((f, i) => api.tone(f, step * 1.6, type, vol, 0, i * step));
return api;
};
})(typeof window !== 'undefined' ? window : globalThis);