Online co-op browser remake of Arknights' Stronghold Protocol: Alliance (client-simulated combat, official waves/bonds/items/strategies, 3D board, facing wheel, operator loadout, official emotes, deployment scripts).
170 lines
7.8 KiB
JavaScript
170 lines
7.8 KiB
JavaScript
// Audio manager (public/js/audio.js): BGM selection, manifest resolution, SFX limiter, and the manager's
|
|
// never-throw behaviour with a fake Web Audio implementation.
|
|
|
|
import { test, describe } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { readFileSync } from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { bgmKeyFor, resolveBgm, SfxLimiter, AudioManager } from '../../public/js/audio.js';
|
|
import { PHASE } from '../../shared/constants.js';
|
|
|
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
|
|
const manifest = JSON.parse(readFileSync(path.join(ROOT, 'data', 'assets.json'), 'utf8'));
|
|
|
|
describe('bgm selection', () => {
|
|
test('route and phase → key', () => {
|
|
assert.equal(bgmKeyFor('title', null), 'lobby');
|
|
assert.equal(bgmKeyFor('room', null), 'lobby');
|
|
assert.equal(bgmKeyFor('game', null), 'lobby');
|
|
assert.equal(bgmKeyFor('game', { phase: PHASE.INFO_CHECK }), 'lobby');
|
|
assert.equal(bgmKeyFor('game', { phase: PHASE.PREP }), 'prep');
|
|
assert.equal(bgmKeyFor('game', { phase: PHASE.SP_DRAFT }), 'prep');
|
|
assert.equal(bgmKeyFor('game', { phase: PHASE.COMBAT }), 'combat');
|
|
assert.equal(bgmKeyFor('game', { phase: PHASE.UNITE }), 'combat');
|
|
assert.equal(bgmKeyFor('game', { phase: PHASE.FINAL_ASSAULT, bossId: 'boss_4' }), 'boss:boss_4');
|
|
assert.equal(bgmKeyFor('game', { phase: PHASE.FINAL_ASSAULT }), 'boss');
|
|
assert.equal(bgmKeyFor('game', { phase: PHASE.HIDDEN_CORE, bossId: 'boss_1', hiddenBossId: 'boss_9' }), 'boss:boss_9');
|
|
assert.equal(bgmKeyFor('game', { phase: PHASE.RESULT }), 'lobby');
|
|
assert.equal(bgmKeyFor('weird', null), null);
|
|
});
|
|
test('resolveBgm uses the manifest (boss fallback, intro optional)', () => {
|
|
const lobby = resolveBgm(manifest, 'lobby');
|
|
assert.ok(lobby && typeof lobby.loop === 'string');
|
|
const b4 = resolveBgm(manifest, 'boss:boss_4');
|
|
assert.equal(b4.loop, manifest.audio.bossBgm.boss_4.loop);
|
|
assert.equal(resolveBgm(manifest, 'boss:nope').loop, manifest.audio.bgm.boss.loop);
|
|
assert.equal(resolveBgm(manifest, 'prep').intro, manifest.audio.bgm.prep.intro ?? null);
|
|
assert.equal(resolveBgm(null, 'lobby'), null);
|
|
assert.equal(resolveBgm(manifest, null), null);
|
|
assert.equal(resolveBgm(manifest, 'nope'), null);
|
|
});
|
|
});
|
|
|
|
describe('SfxLimiter', () => {
|
|
test('caps concurrent voices', () => {
|
|
const l = new SfxLimiter({ maxVoices: 3, unitCooldownMs: 0, urlGapMs: 0 });
|
|
assert.ok(l.tryAcquire(0, 1, 'a'));
|
|
assert.ok(l.tryAcquire(0, 2, 'b'));
|
|
assert.ok(l.tryAcquire(0, 3, 'c'));
|
|
assert.equal(l.tryAcquire(0, 4, 'd'), false);
|
|
l.release();
|
|
assert.ok(l.tryAcquire(0, 4, 'd'));
|
|
l.release(); l.release(); l.release(); l.release(); l.release();
|
|
assert.equal(l.active, 0, 'never negative');
|
|
});
|
|
test('per-unit cooldown and per-url gap', () => {
|
|
const l = new SfxLimiter({ maxVoices: 99, unitCooldownMs: 100, urlGapMs: 30 });
|
|
assert.ok(l.tryAcquire(0, 'u1', 'x'));
|
|
assert.equal(l.tryAcquire(50, 'u1', 'y'), false, 'same unit too soon');
|
|
assert.equal(l.tryAcquire(10, 'u2', 'x'), false, 'same url too soon');
|
|
assert.ok(l.tryAcquire(40, 'u2', 'x'));
|
|
assert.ok(l.tryAcquire(120, 'u1', 'z'));
|
|
assert.ok(l.tryAcquire(121, null, 'w'), 'no unit key ⇒ only url gap');
|
|
});
|
|
});
|
|
|
|
// ---- fake Web Audio -------------------------------------------------------------------------------------
|
|
|
|
function fakeWindow() {
|
|
const listeners = new Map();
|
|
const made = { sources: 0, started: 0 };
|
|
class Param { constructor() { this.value = 1; } setValueAtTime(v) { this.value = v; } linearRampToValueAtTime(v) { this.value = v; } setTargetAtTime(v) { this.value = v; } cancelScheduledValues() {} }
|
|
class Node { connect() {} disconnect() {} }
|
|
class Gain extends Node { constructor() { super(); this.gain = new Param(); } }
|
|
class Src extends Node { constructor() { super(); this.playbackRate = new Param(); made.sources++; } start() { made.started++; } stop() {} }
|
|
class Ctx {
|
|
constructor() { this.currentTime = 0; this.state = 'running'; this.destination = new Node(); }
|
|
createGain() { return new Gain(); }
|
|
createBufferSource() { return new Src(); }
|
|
decodeAudioData(ab, ok) { ok({ duration: 1.5 }); }
|
|
resume() { return Promise.resolve(); }
|
|
suspend() { return Promise.resolve(); }
|
|
}
|
|
return {
|
|
made,
|
|
win: {
|
|
AudioContext: Ctx,
|
|
document: { hidden: false, addEventListener() {} },
|
|
addEventListener(t, fn) { listeners.set(t, fn); },
|
|
removeEventListener(t) { listeners.delete(t); },
|
|
},
|
|
fire(t) { listeners.get(t)?.(); },
|
|
};
|
|
}
|
|
|
|
describe('AudioManager', () => {
|
|
test('no AudioContext / no manifest: every call is a silent no-op', () => {
|
|
const a = new AudioManager({ win: null, getManifest: () => null });
|
|
a.install();
|
|
a.playBgm('prep');
|
|
a.sfx('buy');
|
|
a.battle('enemyDie');
|
|
assert.equal(a.unit('char_x', 'attack', 1), false);
|
|
a.handleBattleEvents([['atk', 1, 2, 'arrow'], 'junk', null]);
|
|
a.setVolumes({ bgm: 5, sfx: -1, muted: true });
|
|
assert.deepEqual(a.volumes, { bgm: 1, sfx: 0, muted: true });
|
|
assert.equal(a.unlocked, false);
|
|
});
|
|
test('unlocks on the first gesture, then plays BGM and SFX from the manifest', async () => {
|
|
const fw = fakeWindow();
|
|
const origFetch = globalThis.fetch;
|
|
const urls = [];
|
|
globalThis.fetch = async (u) => { urls.push(u); return { ok: true, arrayBuffer: async () => new ArrayBuffer(8) }; };
|
|
try {
|
|
const a = new AudioManager({ win: fw.win, getManifest: () => manifest });
|
|
a.install();
|
|
a.playBgm('prep'); // remembered while locked
|
|
assert.equal(urls.length, 0);
|
|
fw.fire('pointerdown');
|
|
assert.equal(a.unlocked, true);
|
|
await new Promise((r) => setTimeout(r, 10));
|
|
assert.ok(urls.includes(manifest.audio.bgm.prep.loop), 'BGM fetched after unlock');
|
|
a.sfx('buy');
|
|
a.sfx('nonexistent');
|
|
await new Promise((r) => setTimeout(r, 10));
|
|
assert.ok(urls.includes(manifest.audio.sfx.ui.buy));
|
|
// same loop URL ⇒ no restart
|
|
const before = fw.made.started;
|
|
a.playBgm('combat');
|
|
await new Promise((r) => setTimeout(r, 10));
|
|
assert.equal(fw.made.started, before, 'prep → combat shares the loop');
|
|
// battle events map to unit sounds (UnitInfo.spine = char id)
|
|
const charId = Object.keys(manifest.audio.sfx.units).find((k) => manifest.audio.sfx.units[k].attack && k.startsWith('char_'));
|
|
a.setFieldUnits([{ id: 1, side: 'ally', spine: charId }, { id: 2, side: 'enemy', spine: 'enemy_nope' }]);
|
|
a.handleBattleEvents([['atk', 1, 2, 'arrow'], ['dmg', 2, 100, 'phys'], ['die', 2], ['spawn', { id: 3, side: 'enemy', spine: 'x' }], ['bounty', 'p', 1]]);
|
|
await new Promise((r) => setTimeout(r, 10));
|
|
assert.ok(urls.includes(manifest.audio.sfx.units[charId].attack));
|
|
assert.ok(urls.includes(manifest.audio.sfx.battle.enemyDie), 'fallback death sound');
|
|
assert.ok(a.limiter.active <= a.limiter.maxVoices);
|
|
a.setVolumes({ muted: true });
|
|
const n = urls.length;
|
|
a.sfx('refresh');
|
|
assert.equal(urls.length, n, 'muted ⇒ nothing requested');
|
|
} finally {
|
|
globalThis.fetch = origFetch;
|
|
}
|
|
});
|
|
test('fetch failures are swallowed', async () => {
|
|
const fw = fakeWindow();
|
|
const origFetch = globalThis.fetch;
|
|
globalThis.fetch = async () => { throw new Error('offline'); };
|
|
const origWarn = console.warn;
|
|
let warns = 0;
|
|
console.warn = () => { warns++; };
|
|
try {
|
|
const a = new AudioManager({ win: fw.win, getManifest: () => manifest });
|
|
a.install();
|
|
fw.fire('keydown');
|
|
a.playBgm('lobby');
|
|
a.sfx('buy');
|
|
a.sfx('buy');
|
|
await new Promise((r) => setTimeout(r, 20));
|
|
assert.ok(warns >= 1);
|
|
} finally {
|
|
globalThis.fetch = origFetch;
|
|
console.warn = origWarn;
|
|
}
|
|
});
|
|
});
|