Co-op (QA'd with two to three real browsers, TCP-proxy chaos scenarios): - partner's tower changes are never dropped after a render stall or snapshot burst - half-open connections show "reconnecting" in ~6 s instead of 45-65 s - upgrade and next-wave are idempotent (stale commands refused), restart message, promoted host gets Play again, failed joins never kill a live game, listener leaks Audio / keyboard / a11y: - one Audio element per track, fade/stinger supersede tokens, play() retry on the next gesture, 5 s fallback to the synth, mute works everywhere, dialogs with role/aria-modal/focus handling, accessible names for sound/speed/pause New content: - enemies: Daemon (healer), Proxy (regenerating shield), Botnet (flyer swarm); waves weave them in from wave 9 (waves 1-8 unchanged) - towers: Sandbox (stun pulse), Load Balancer (fire-rate aura); hotkeys 1-9 - glyphs/shapes, stun/heal effects, gallery e2e that pixel-checks every kind Orbital Uplink rebalanced after playtesting (was affordable by wave ~6 and buyable in bulk from boss rewards): 1500 credits, upgrades 1200/2000/3200, and every Uplink already owned makes the next one 25% dearer to buy AND to upgrade (each tower remembers its multiplier, carried in the tower list as a 9th field). Shared TD.priceFor/upgradePrice so the UI shows exactly what the sim charges. Also: tablet/foldable viewports in the layout matrix (tolerant colour check), docs (README tower/enemy tables, PROTOCOL shield/stun/pm encodings, NEXT roadmap). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
401 lines
22 KiB
JavaScript
401 lines
22 KiB
JavaScript
/*
|
|
* NETWALL audio: synthesised sound effects + background music.
|
|
*
|
|
* Music: looks for assets/music/<track>.mp3 (or .ogg) - tracks: theme (menu), battle, boss - plus one-shot
|
|
* stingers win / lose. Any track that is missing falls back to a small generative synth melody, so the game
|
|
* has music out of the box and a Suno-made file simply replaces it when you drop it in.
|
|
*/
|
|
(function (root) {
|
|
'use strict';
|
|
const NW = root.NW = root.NW || {};
|
|
|
|
const MUSIC_DIR = 'assets/music/';
|
|
const STORE = 'nw.audio';
|
|
|
|
let ctx = null, master = null, sfxBus = null, musBus = null, delayNode = null;
|
|
let muted = false, musicVol = 0.55, sfxVol = 0.8;
|
|
let unlocked = false;
|
|
let wanted = null; // music track the game currently wants ('theme' | 'battle' | 'boss' | null)
|
|
let current = null; // { name, kind:'file'|'synth', el?, stop() }
|
|
const lastPlay = {};
|
|
|
|
try {
|
|
const s = JSON.parse(localStorage.getItem(STORE) || '{}');
|
|
if (typeof s.muted === 'boolean') muted = s.muted;
|
|
if (typeof s.music === 'number') musicVol = Math.min(1, Math.max(0, s.music));
|
|
} catch (e) { /* storage unavailable */ }
|
|
function save() { try { localStorage.setItem(STORE, JSON.stringify({ muted, music: musicVol })); } catch (e) { /* ignore */ } }
|
|
|
|
function ensureCtx() {
|
|
if (ctx) return ctx;
|
|
const AC = root.AudioContext || root.webkitAudioContext;
|
|
if (!AC) return null;
|
|
try { ctx = new AC(); } catch (e) { return null; }
|
|
master = ctx.createGain(); master.gain.value = muted ? 0 : 0.9;
|
|
master.connect(ctx.destination);
|
|
sfxBus = ctx.createGain(); sfxBus.gain.value = 0.32 * sfxVol; sfxBus.connect(master);
|
|
musBus = ctx.createGain(); musBus.gain.value = 0.3 * musicVol; musBus.connect(master);
|
|
return ctx;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- sfx
|
|
function tone(freq, dur, type, vol, slideTo, when) {
|
|
if (!ctx || muted) return;
|
|
const t0 = ctx.currentTime + (when || 0);
|
|
const o = ctx.createOscillator(), g = ctx.createGain();
|
|
o.type = type || 'square';
|
|
o.frequency.setValueAtTime(freq, t0);
|
|
if (slideTo) o.frequency.exponentialRampToValueAtTime(Math.max(20, slideTo), t0 + dur);
|
|
g.gain.setValueAtTime(0.0001, t0);
|
|
g.gain.exponentialRampToValueAtTime(vol, t0 + 0.008);
|
|
g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur);
|
|
o.connect(g); g.connect(sfxBus);
|
|
o.start(t0); o.stop(t0 + dur + 0.02);
|
|
}
|
|
let noiseBuf = null;
|
|
function noiseBuffer() {
|
|
if (noiseBuf) return noiseBuf;
|
|
noiseBuf = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
|
|
const d = noiseBuf.getChannelData(0);
|
|
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
|
|
return noiseBuf;
|
|
}
|
|
function noise(dur, vol, filterType, f0, f1, when, bus) {
|
|
if (!ctx || muted) return;
|
|
const t0 = ctx.currentTime + (when || 0);
|
|
const s = ctx.createBufferSource(); s.buffer = noiseBuffer();
|
|
const f = ctx.createBiquadFilter(); f.type = filterType || 'lowpass';
|
|
f.frequency.setValueAtTime(f0, t0);
|
|
if (f1) f.frequency.exponentialRampToValueAtTime(f1, t0 + dur);
|
|
const g = ctx.createGain();
|
|
g.gain.setValueAtTime(vol, t0);
|
|
g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur);
|
|
s.connect(f); f.connect(g); g.connect(bus || sfxBus);
|
|
s.start(t0, Math.random() * 0.5); s.stop(t0 + dur + 0.02);
|
|
}
|
|
|
|
const SFX = {
|
|
click: () => tone(660, 0.04, 'square', 0.12),
|
|
place: () => { tone(420, 0.07, 'square', 0.22, 700); noise(0.05, 0.12, 'highpass', 3000); },
|
|
wall: () => tone(240, 0.05, 'square', 0.16, 330),
|
|
sell: () => tone(560, 0.12, 'triangle', 0.22, 220),
|
|
up: () => { tone(520, 0.08, 'square', 0.18); tone(780, 0.08, 'square', 0.18, 0, 0.07); tone(1040, 0.14, 'square', 0.18, 0, 0.14); },
|
|
error: () => { tone(190, 0.1, 'square', 0.2); tone(150, 0.12, 'square', 0.2, 0, 0.09); },
|
|
shot_filter: () => noise(0.03, 0.07, 'highpass', 5000),
|
|
shot_ids: () => { tone(1100, 0.14, 'sawtooth', 0.2, 180); noise(0.08, 0.12, 'highpass', 2500); },
|
|
shot_mortar: () => tone(150, 0.18, 'sine', 0.45, 60),
|
|
// Orbital Uplink: a falling laser sweep over a sub-bass thump and a hiss of ionised air
|
|
shot_uplink: () => { tone(2600, 0.45, 'sawtooth', 0.16, 140); tone(1300, 0.45, 'square', 0.07, 70, 0.02); tone(70, 0.55, 'sine', 0.5, 32); noise(0.4, 0.22, 'bandpass', 4200, 600); },
|
|
arc: () => { noise(0.1, 0.16, 'bandpass', 3500, 900); tone(900, 0.08, 'sawtooth', 0.1, 300); },
|
|
boom: () => noise(0.32, 0.5, 'lowpass', 1800, 90),
|
|
kill: () => tone(820, 0.05, 'triangle', 0.1, 1200),
|
|
leak: () => { tone(320, 0.35, 'sawtooth', 0.3, 70); noise(0.25, 0.25, 'lowpass', 900, 100); },
|
|
wave: () => { tone(220, 0.35, 'sawtooth', 0.14, 330); tone(330, 0.35, 'sawtooth', 0.12, 495, 0.05); tone(440, 0.45, 'sawtooth', 0.1, 660, 0.1); },
|
|
boss: () => { tone(110, 0.8, 'sawtooth', 0.28, 55); tone(116, 0.8, 'sawtooth', 0.22, 58); noise(0.6, 0.2, 'lowpass', 600, 80); },
|
|
clear: () => { tone(660, 0.09, 'triangle', 0.2); tone(880, 0.09, 'triangle', 0.2, 0, 0.09); tone(1320, 0.2, 'triangle', 0.2, 0, 0.18); },
|
|
ping: () => { tone(1320, 0.18, 'sine', 0.25, 1760); tone(1760, 0.3, 'sine', 0.12, 0, 0.12); },
|
|
join: () => { tone(660, 0.1, 'triangle', 0.2); tone(990, 0.16, 'triangle', 0.2, 0, 0.1); },
|
|
};
|
|
const MIN_GAP = { shot_uplink: 0.12, shot_filter: 0.06, kill: 0.05, arc: 0.07, boom: 0.08, shot_mortar: 0.1, shot_ids: 0.08, wall: 0.03 };
|
|
|
|
function sfx(name) {
|
|
if (muted || !unlocked || !ctx || !SFX[name]) return;
|
|
const now = ctx.currentTime, gap = MIN_GAP[name] || 0;
|
|
if (gap && lastPlay[name] && now - lastPlay[name] < gap) return;
|
|
lastPlay[name] = now;
|
|
SFX[name]();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- generative music (fallback)
|
|
const NOTE = (n) => 440 * Math.pow(2, (n - 69) / 12); // midi -> Hz
|
|
const PROGS = {
|
|
theme: { bpm: 76, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], bass: [45, 41, 36, 43] },
|
|
battle: { bpm: 112, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], bass: [45, 41, 36, 43] },
|
|
boss: { bpm: 138, chords: [[57, 60, 64], [57, 60, 64], [53, 57, 60], [52, 56, 59]], bass: [45, 45, 41, 40] },
|
|
};
|
|
const ARP = [0, 1, 2, 1, 2, 1, 2, 0, 1, 2, 1, 2, 1, 0, 2, 1]; // chord-tone index per 16th
|
|
|
|
function startSynth(name) {
|
|
const p = PROGS[name] || PROGS.battle;
|
|
const out = ctx.createGain(); out.gain.value = 0.0001; out.connect(musBus);
|
|
out.gain.exponentialRampToValueAtTime(1, ctx.currentTime + 1.5);
|
|
const delay = ctx.createDelay(1.0); delay.delayTime.value = 60 / p.bpm * 0.75;
|
|
const fb = ctx.createGain(); fb.gain.value = 0.38; delay.connect(fb); fb.connect(delay);
|
|
const wet = ctx.createGain(); wet.gain.value = 0.5; delay.connect(wet); wet.connect(out);
|
|
const sixteenth = 60 / p.bpm / 4;
|
|
let step = 0, next = ctx.currentTime + 0.1, timer = 0, dead = false;
|
|
|
|
function note(type, freq, t, dur, vol, cutoff, dest) {
|
|
const o = ctx.createOscillator(), f = ctx.createBiquadFilter(), g = ctx.createGain();
|
|
o.type = type; o.frequency.value = freq;
|
|
f.type = 'lowpass'; f.frequency.value = cutoff; f.Q.value = 2;
|
|
g.gain.setValueAtTime(0.0001, t);
|
|
g.gain.exponentialRampToValueAtTime(vol, t + Math.min(0.02, dur / 3));
|
|
g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
|
|
o.connect(f); f.connect(g); g.connect(dest || out);
|
|
o.start(t); o.stop(t + dur + 0.05);
|
|
}
|
|
function pad(chord, t, dur) {
|
|
for (const n of chord) {
|
|
for (const det of [-7, 7]) {
|
|
const o = ctx.createOscillator(), f = ctx.createBiquadFilter(), g = ctx.createGain();
|
|
o.type = 'sawtooth'; o.frequency.value = NOTE(n + 12); o.detune.value = det;
|
|
f.type = 'lowpass'; f.frequency.setValueAtTime(500, t); f.frequency.linearRampToValueAtTime(1400, t + dur * 0.5); f.frequency.linearRampToValueAtTime(600, t + dur);
|
|
g.gain.setValueAtTime(0.0001, t);
|
|
g.gain.linearRampToValueAtTime(0.05, t + dur * 0.3);
|
|
g.gain.linearRampToValueAtTime(0.0001, t + dur);
|
|
o.connect(f); f.connect(g); g.connect(out);
|
|
o.start(t); o.stop(t + dur + 0.05);
|
|
}
|
|
}
|
|
}
|
|
function kick(t) {
|
|
const o = ctx.createOscillator(), g = ctx.createGain();
|
|
o.type = 'sine'; o.frequency.setValueAtTime(140, t); o.frequency.exponentialRampToValueAtTime(42, t + 0.12);
|
|
g.gain.setValueAtTime(0.9, t); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.22);
|
|
o.connect(g); g.connect(out); o.start(t); o.stop(t + 0.25);
|
|
}
|
|
|
|
function schedule() {
|
|
if (dead) return;
|
|
while (next < ctx.currentTime + 0.25) {
|
|
const bar = Math.floor(step / 16) % p.chords.length, s = step % 16;
|
|
const chord = p.chords[bar], t = next;
|
|
if (s === 0) pad(chord, t, sixteenth * 16 * 1.02);
|
|
if (name !== 'theme' || s % 4 === 0) {
|
|
// arpeggio, quieter and sparser for the menu theme
|
|
const idx = ARP[s], n = chord[idx % 3] + 12 * (idx === 2 ? 1 : 0) + 12;
|
|
const pat = name === 'theme' ? (s % 8 === 0) : (name === 'boss' ? true : (s % 2 === 0 || s % 16 === 15));
|
|
if (pat) note('square', NOTE(n), t, sixteenth * 1.6, name === 'theme' ? 0.05 : 0.06, 2600, delay);
|
|
if (pat) note('square', NOTE(n), t, sixteenth * 1.6, 0.03, 2600);
|
|
}
|
|
if (name !== 'theme') {
|
|
if (s % 2 === 0) note('sawtooth', NOTE(p.bass[bar] + (s % 8 === 6 ? 12 : 0)), t, sixteenth * 1.7, 0.16, 420);
|
|
if (s % 4 === 0) kick(t);
|
|
if (s % 4 === 2) noise(0.05, 0.12, 'highpass', 7000, 0, t - ctx.currentTime, out);
|
|
if (name === 'boss' && s % 8 === 4) noise(0.12, 0.2, 'bandpass', 1800, 900, t - ctx.currentTime, out);
|
|
} else if (s === 0) {
|
|
note('sine', NOTE(p.bass[bar]), t, sixteenth * 14, 0.22, 300);
|
|
}
|
|
step++; next += sixteenth;
|
|
}
|
|
}
|
|
timer = setInterval(schedule, 40);
|
|
schedule();
|
|
return {
|
|
name, kind: 'synth',
|
|
stop(fade) {
|
|
dead = true; clearInterval(timer);
|
|
const t = ctx.currentTime;
|
|
out.gain.cancelScheduledValues(t);
|
|
out.gain.setValueAtTime(Math.max(0.0001, out.gain.value), t);
|
|
out.gain.exponentialRampToValueAtTime(0.0001, t + (fade || 0.8));
|
|
setTimeout(() => { try { out.disconnect(); } catch (e) { /* ignore */ } }, ((fade || 0.8) + 0.2) * 1000);
|
|
},
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------- file music
|
|
// assets/music/tracks.json maps track names to file names, e.g. {"battle": "my-song.mp3"}; null = use the synth.
|
|
// Reading one small manifest (instead of probing for files) keeps the console free of 404s.
|
|
//
|
|
// Rules that keep the sound right when the game asks for music faster than a file loads or a fade finishes:
|
|
// * every track has ONE element for the whole session, created the first time it is asked for (not when it can play), so
|
|
// rapid music() calls share one download (code-16);
|
|
// * a fade belongs to its element and any newer fade or restart cancels it, so a stale fade-out can never pause a track that
|
|
// was started again (code-7); the stinger has its own supersede token (code-12);
|
|
// * a file that is not playable within timing.load ms (stalled, or broken) is replaced by the synth at once, and the file is
|
|
// tried again the next time that track is wanted (code-15);
|
|
// * a play() the browser refuses (iOS / Safari autoplay rules) is retried inside the next tap, click or key press (code-14).
|
|
const timing = { load: 5000, sting: 2500, retry: 15000 }; // ms: wait for a music file / for a stinger / before retrying a file that errored
|
|
let manifestData = null, manifestP = null, manifestTried = -1e9;
|
|
function manifest() { // resolves to the manifest, or null when it could not be read (never latched: it is asked again later)
|
|
if (manifestData) return Promise.resolve(manifestData);
|
|
if (manifestP) return manifestP;
|
|
if (!(typeof fetch === 'function' && root.location && /^https?:/.test(root.location.protocol))) { manifestData = {}; return Promise.resolve(manifestData); }
|
|
if (Date.now() - manifestTried < timing.retry) return Promise.resolve(null);
|
|
manifestTried = Date.now();
|
|
manifestP = fetch(MUSIC_DIR + 'tracks.json', { cache: 'no-cache' })
|
|
.then((r) => (r.ok ? r.json() : r.status === 404 ? {} : null)) // no manifest at all = no files: synth for good; a server error is asked again later
|
|
.catch(() => null)
|
|
.then((m) => { manifestP = null; if (m && typeof m === 'object') manifestData = m; return manifestData; });
|
|
return manifestP;
|
|
}
|
|
manifest(); // (read it up front: the first tap can then create the element and call play() inside the gesture, which iOS insists on)
|
|
function fileName(name) {
|
|
const f = manifestData && manifestData[name];
|
|
return typeof f === 'string' && /^[\w .()-]+\.(mp3|ogg|m4a|wav)$/i.test(f) ? f : null;
|
|
}
|
|
const tracks = {}; // name -> { el, state: 'loading' | 'ready' | 'failed', failedAt }
|
|
// The element of a track; null when the manifest names no file for it. A failed one is tried again after timing.retry.
|
|
function track(name) {
|
|
let t = tracks[name];
|
|
if (t && t.state === 'failed' && Date.now() - t.failedAt > timing.retry) { try { t.el.removeAttribute('src'); t.el.load(); } catch (e) { /* ignore */ } t = tracks[name] = null; }
|
|
if (t) return t;
|
|
const f = fileName(name);
|
|
if (!f) return null;
|
|
const el = new Audio();
|
|
t = tracks[name] = { name, el, state: 'loading', failedAt: 0 };
|
|
el.preload = 'auto';
|
|
el.loop = name !== 'win' && name !== 'lose';
|
|
el.addEventListener('canplay', () => { if (t.state === 'loading') t.state = 'ready'; });
|
|
el.addEventListener('error', () => { if (tracks[name] === t) { t.state = 'failed'; t.failedAt = Date.now(); } });
|
|
el.src = MUSIC_DIR + encodeURIComponent(f).replace(/%2F/g, '/');
|
|
return t;
|
|
}
|
|
// Starts a track the player is not listening to yet (the boss theme before the boss, the stingers before the end). Cheap files only
|
|
// unless the connection allows it: Data Saver and 2G/3G skip it.
|
|
function preload(name) {
|
|
const c = root.navigator && root.navigator.connection;
|
|
if (c && (c.saveData || /(^|-)[23]g$/.test(c.effectiveType || ''))) return;
|
|
manifest().then(() => { if (manifestData) track(name); });
|
|
}
|
|
|
|
const fades = new WeakMap(); // element -> the fade running on it (a token object)
|
|
function cancelFade(el) { fades.delete(el); }
|
|
function fadeEl(el, to, ms, done) {
|
|
const mine = {}; fades.set(el, mine);
|
|
const from = el.volume, t0 = performance.now();
|
|
const step = () => {
|
|
if (fades.get(el) !== mine) return; // superseded: a newer fade or a restart owns the element now
|
|
const k = ms > 0 ? Math.min(1, (performance.now() - t0) / ms) : 1;
|
|
try { el.volume = Math.max(0, Math.min(1, from + (to - from) * k)); } catch (e) { /* ignore */ }
|
|
if (k < 1) setTimeout(step, 33); else { fades.delete(el); if (done) done(); } // (a timer, not rAF: a hidden tab must still finish its fade-out)
|
|
};
|
|
step();
|
|
}
|
|
const pauseEl = (el) => { try { el.pause(); } catch (e) { /* ignore */ } };
|
|
|
|
let blocked = false; // the browser refused play(): the next gesture retries (code-14)
|
|
let stingersLoaded = false; // the end-screen stingers are fetched once, after the first battle track plays
|
|
function stopCurrent(fade) {
|
|
const c = current; current = null;
|
|
if (!c) return;
|
|
clearTimeout(c.timer);
|
|
if (c.kind === 'synth') c.stop(fade);
|
|
else if (c.el) fadeEl(c.el, 0, (fade || 0.8) * 1000, () => { if (!(current && current.el === c.el)) pauseEl(c.el); });
|
|
}
|
|
// The generative melody stands in for a track whose file is missing, broken or too slow.
|
|
function useSynth(tok) {
|
|
clearTimeout(tok.timer);
|
|
if (current !== tok) return;
|
|
if (tok.el) { cancelFade(tok.el); pauseEl(tok.el); } // the file may still arrive: it must not start on top of the synth
|
|
const c = ensureCtx();
|
|
current = c ? startSynth(tok.name) : null;
|
|
if (current) current.name = tok.name;
|
|
}
|
|
function playFile(t, tok, keepPos) {
|
|
const el = t.el;
|
|
tok.el = el;
|
|
cancelFade(el);
|
|
if (el.paused && !keepPos) { try { el.currentTime = 0; } catch (e) { /* not seekable yet */ } el.volume = 0; } // (a track still playing, e.g. a mute undone during its fade-out, carries on)
|
|
let pr;
|
|
try { pr = el.play(); } catch (e) { pr = Promise.reject(e); }
|
|
const ok = () => {
|
|
if (current !== tok) return;
|
|
clearTimeout(tok.timer);
|
|
tok.kind = 'file';
|
|
fadeEl(el, 0.8 * musicVol, 1200);
|
|
if (tok.name === 'battle' && !stingersLoaded) { stingersLoaded = true; setTimeout(() => { preload('lose'); preload('win'); }, 1500); }
|
|
};
|
|
const bad = (err) => {
|
|
if (current !== tok) return;
|
|
const why = err && err.name;
|
|
if (why === 'AbortError') return; // paused or reloaded under it (tab hidden): the visible handler starts it again
|
|
if (why === 'NotAllowedError') { clearTimeout(tok.timer); pauseEl(el); current = null; blocked = true; return; }
|
|
t.state = 'failed'; t.failedAt = Date.now();
|
|
useSynth(tok);
|
|
};
|
|
if (pr && pr.then) pr.then(ok, bad); else ok();
|
|
}
|
|
|
|
function applyMusic() {
|
|
if (!unlocked) return;
|
|
if (wanted) stopStinger(0.8);
|
|
if (!wanted || muted) { stopCurrent(0.4); return; }
|
|
if (current && current.name === wanted) return;
|
|
const name = wanted;
|
|
stopCurrent(0.9);
|
|
const tok = current = { name, kind: 'pending', stop() {}, el: null, timer: 0 }; // placeholder: rapid calls do not stack, a late answer is ignored
|
|
tok.timer = setTimeout(() => { if (current === tok) useSynth(tok); }, timing.load);
|
|
const go = () => {
|
|
const t = track(name);
|
|
if (!t || t.state === 'failed') useSynth(tok); else playFile(t, tok);
|
|
};
|
|
if (manifestData) { go(); return; } // (synchronously, so that play() is still inside the tap)
|
|
manifest().then(() => { if (current === tok) go(); });
|
|
}
|
|
|
|
let stingEl = null, stingTok = 0;
|
|
function stopStinger(fade) {
|
|
stingTok++;
|
|
const el = stingEl; stingEl = null;
|
|
if (el) fadeEl(el, 0, (fade || 0.6) * 1000, () => { if (stingEl !== el) pauseEl(el); });
|
|
}
|
|
function jingle(name) { // the synth stinger, also what plays when the file is missing, late or refused
|
|
if (muted || !ctx) return;
|
|
if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); }
|
|
else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); }
|
|
}
|
|
function stinger(name) {
|
|
if (muted || !unlocked) return;
|
|
stopStinger(0.2);
|
|
const tok = stingTok, t = manifestData ? track(name) : null;
|
|
if (!t || t.state === 'failed') { jingle(name); return; }
|
|
const el = t.el;
|
|
stingEl = el; cancelFade(el);
|
|
try { el.currentTime = 0; } catch (e) { /* not seekable yet */ }
|
|
el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol));
|
|
const fail = () => { if (tok !== stingTok) return; stingEl = null; cancelFade(el); pauseEl(el); jingle(name); };
|
|
const timer = setTimeout(fail, timing.sting); // not playing yet after this long: the synth jingle stands in, the file is dropped
|
|
let pr;
|
|
try { pr = el.play(); } catch (e) { pr = Promise.reject(e); }
|
|
if (pr && pr.then) pr.then(() => clearTimeout(timer), (err) => { clearTimeout(timer); if (!(err && err.name === 'AbortError')) fail(); });
|
|
}
|
|
|
|
// ---------------------------------------------------------------- public
|
|
function unlock() {
|
|
const c = ensureCtx();
|
|
if (c && c.state !== 'running' && c.state !== 'closed') { try { const p = c.resume(); if (p && p.catch) p.catch(() => {}); } catch (e) { /* ignore */ } }
|
|
if (!unlocked) { unlocked = true; applyMusic(); return; }
|
|
if (blocked) { blocked = false; applyMusic(); } // a refused play() is retried at every gesture until it is allowed (code-14)
|
|
}
|
|
|
|
// Every kind of gesture, in the capture phase: pointerdown alone is no gesture for a finger (touch needs pointerup / touchend / click).
|
|
for (const ev of ['pointerdown', 'pointerup', 'touchend', 'click', 'keydown']) root.addEventListener(ev, unlock, { passive: true, capture: true });
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (document.hidden) {
|
|
if (ctx && ctx.suspend) ctx.suspend();
|
|
if (current && current.el) pauseEl(current.el);
|
|
if (stingEl) pauseEl(stingEl);
|
|
} else {
|
|
if (ctx && ctx.resume) ctx.resume();
|
|
if (current && current.el && !muted) { const t = tracks[current.name]; if (t && t.el === current.el) playFile(t, current, true); }
|
|
}
|
|
});
|
|
|
|
NW.Audio = {
|
|
sfx,
|
|
unlock,
|
|
stinger,
|
|
preload,
|
|
timing, // tunable for tests
|
|
get muted() { return muted; },
|
|
get now() { return current ? { name: current.name, kind: current.kind } : null; }, // for tests / debugging
|
|
get blocked() { return blocked; },
|
|
setMuted(m) {
|
|
muted = !!m; save();
|
|
if (master) master.gain.value = muted ? 0 : 0.9;
|
|
if (muted) { stopCurrent(0.2); stopStinger(0.2); } else applyMusic();
|
|
},
|
|
toggleMuted() { this.setMuted(!muted); return muted; },
|
|
// Which music the game wants right now: 'theme' | 'battle' | 'boss' | null
|
|
music(name) { wanted = name; applyMusic(); },
|
|
get musicVolume() { return musicVol; },
|
|
setMusicVolume(v) {
|
|
musicVol = Math.min(1, Math.max(0, v)); save();
|
|
if (musBus) musBus.gain.value = 0.3 * musicVol;
|
|
if (current && current.kind === 'file') { cancelFade(current.el); current.el.volume = 0.8 * musicVol; }
|
|
},
|
|
};
|
|
})(typeof self !== 'undefined' ? self : this);
|