diff --git a/src/main/java/org/scape2006/web/DesktopHooks.java b/src/main/java/org/scape2006/web/DesktopHooks.java index 2e9c3aa..ffc7fb3 100644 --- a/src/main/java/org/scape2006/web/DesktopHooks.java +++ b/src/main/java/org/scape2006/web/DesktopHooks.java @@ -107,12 +107,13 @@ public final class DesktopHooks { public static void playSound(byte[] buffer, int offset, int length, int level, int delay) { if (buffer == null || length <= 0 || offset + length > buffer.length) return; + float vol = soundVolume * Math.max(0f, Math.min(1f, level / 100.0f)); + if (vol <= 0.0f) return; Uint8Array arr = Uint8Array.create(length); for (int i = 0; i < length; i++) { arr.set(i, (short) (buffer[offset + i] & 0xFF)); } - float vol = soundVolume * Math.max(0f, Math.min(1f, level / 100.0f)); - jsPlayPcm(arr, vol); + jsPlayPcm(arr, vol, Math.max(0, delay)); } public static void setSoundVolume(int config) { @@ -484,9 +485,9 @@ public final class DesktopHooks { } } - @JSBody(params = {"arr", "vol"}, script = - "if (window.scapeWebAudio && window.scapeWebAudio.playPcm) window.scapeWebAudio.playPcm(arr, vol);") - private static native void jsPlayPcm(Uint8Array arr, float vol); + @JSBody(params = {"arr", "vol", "delayMs"}, script = + "if (window.scapeWebAudio && window.scapeWebAudio.playPcm) window.scapeWebAudio.playPcm(arr, vol, delayMs);") + private static native void jsPlayPcm(Uint8Array arr, float vol, int delayMs); @JSBody(params = {"arr", "vol"}, script = "if (window.scapeWebAudio && window.scapeWebAudio.playMidi) window.scapeWebAudio.playMidi(arr, vol);") diff --git a/src/main/webapp/index.html b/src/main/webapp/index.html index 7b9280e..f2beae8 100644 --- a/src/main/webapp/index.html +++ b/src/main/webapp/index.html @@ -428,12 +428,20 @@ synth: null, synthNode: null, synthLoading: null, + synthAssetsLoading: null, synthReady: false, pendingMidi: null, + midiPlaySeq: 0, ensureCtx() { if (!this.ctx) { const AudioCtx = window.AudioContext || window.webkitAudioContext; - if (AudioCtx) this.ctx = new AudioCtx(); + if (AudioCtx) { + try { + this.ctx = new AudioCtx({ latencyHint: 'interactive' }); + } catch (_) { + this.ctx = new AudioCtx(); + } + } } if (this.ctx && this.ctx.state === 'suspended') { this.ctx.resume().then(() => { @@ -446,6 +454,25 @@ } return this.ctx; }, + preloadFluidSynthAssets() { + if (this.synthAssetsLoading) return this.synthAssetsLoading; + if (typeof JSSynth === 'undefined') return Promise.resolve(null); + this.synthAssetsLoading = (async () => { + const [, sfBuf] = await Promise.all([ + JSSynth.waitForReady(), + fetch('TimGM6mb.sf2').then(resp => { + if (!resp || !resp.ok) throw new Error('Failed to fetch TimGM6mb.sf2'); + return resp.arrayBuffer(); + }) + ]); + return sfBuf; + })().catch(e => { + console.warn('FluidSynth preload error:', e); + this.synthAssetsLoading = null; + return null; + }); + return this.synthAssetsLoading; + }, ensureFluidSynth() { if (this.synthReady) return Promise.resolve(this.synth); if (this.synthLoading) return this.synthLoading; @@ -453,12 +480,10 @@ if (!ctx || typeof JSSynth === 'undefined') return Promise.resolve(null); this.synthLoading = (async () => { try { - await JSSynth.waitForReady(); + const sfBuf = await this.preloadFluidSynthAssets(); + if (!sfBuf) throw new Error('SoundFont unavailable'); const s = new JSSynth.Synthesizer(); s.init(ctx.sampleRate); - const resp = await fetch('TimGM6mb.sf2'); - if (!resp || !resp.ok) throw new Error('Failed to fetch TimGM6mb.sf2'); - const sfBuf = await resp.arrayBuffer(); await s.loadSFont(sfBuf); s.setGain(this.midiGain * 0.5); const node = s.createAudioNode(ctx, 4096); @@ -480,23 +505,55 @@ })(); return this.synthLoading; }, - playPcm(bytes, volume) { + decodeWav8MonoSync(ctx, bytes) { + if (!bytes || bytes.length < 44) return null; + if (bytes[0] !== 0x52 || bytes[1] !== 0x49 || bytes[2] !== 0x46 || bytes[3] !== 0x46) return null; // RIFF + if (bytes[8] !== 0x57 || bytes[9] !== 0x41 || bytes[10] !== 0x56 || bytes[11] !== 0x45) return null; // WAVE + const audioFmt = bytes[20] | (bytes[21] << 8); + const channels = bytes[22] | (bytes[23] << 8); + const bitsPerSample = bytes[34] | (bytes[35] << 8); + if (audioFmt !== 1 || channels !== 1 || bitsPerSample !== 8) return null; + if (bytes[36] !== 0x64 || bytes[37] !== 0x61 || bytes[38] !== 0x74 || bytes[39] !== 0x61) return null; // data + const sampleRate = (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16) | (bytes[27] << 24)) >>> 0; + const dataSize = Math.min( + (bytes[40] | (bytes[41] << 8) | (bytes[42] << 16) | (bytes[43] << 24)) >>> 0, + bytes.length - 44 + ); + if (sampleRate < 4000 || dataSize <= 0) return null; + const buf = ctx.createBuffer(1, dataSize, sampleRate); + const out = buf.getChannelData(0); + for (let i = 0; i < dataSize; i++) { + out[i] = (bytes[44 + i] - 128) / 128.0; + } + return buf; + }, + playBuffer(ctx, buf, volume, delayMs) { + const src = ctx.createBufferSource(); + const gain = ctx.createGain(); + gain.gain.value = Math.max(0, Math.min(1, volume)); + src.buffer = buf; + src.connect(gain); + gain.connect(ctx.destination); + const startAt = (delayMs && delayMs > 0) ? (ctx.currentTime + delayMs / 1000.0) : 0; + src.start(startAt); + }, + playPcm(bytes, volume, delayMs) { const ctx = this.ensureCtx(); - if (!ctx || !bytes || bytes.length === 0) return; + if (!ctx || ctx.state === 'suspended' || !bytes || bytes.length === 0) return; + const syncBuf = this.decodeWav8MonoSync(ctx, bytes); + if (syncBuf) { + this.playBuffer(ctx, syncBuf, volume, delayMs); + return; + } const copy = new Uint8Array(bytes).buffer; ctx.decodeAudioData(copy).then(buf => { - const src = ctx.createBufferSource(); - const gain = ctx.createGain(); - gain.gain.value = Math.max(0, Math.min(1, volume)); - src.buffer = buf; - src.connect(gain); - gain.connect(ctx.destination); - src.start(0); + this.playBuffer(ctx, buf, volume, delayMs); }).catch(() => {}); }, async playMidi(bytes, volume) { this.midiGain = Math.max(0, Math.min(1, volume)); if (!bytes || bytes.length === 0) return; + const seq = ++this.midiPlaySeq; this.ensureCtx(); if (!this.synthReady) { this.pendingMidi = new Uint8Array(bytes); @@ -512,8 +569,11 @@ const copy = new Uint8Array(bytes).buffer; this.synth.setGain(this.midiGain * 0.5); await this.synth.stopPlayer(); + if (seq !== this.midiPlaySeq) return; await this.synth.resetPlayer(); + if (seq !== this.midiPlaySeq) return; await this.synth.addSMFDataToPlayer(copy); + if (seq !== this.midiPlaySeq) return; if (this.synth.setPlayerLoop) { this.synth.setPlayerLoop(-1); } @@ -529,12 +589,14 @@ } }, stopMidi() { + this.midiPlaySeq++; this.pendingMidi = null; if (this.synthReady && this.synth) { try { this.synth.stopPlayer(); } catch (_) {} } } }; + window.scapeWebAudio.preloadFluidSynthAssets(); ['pointerdown', 'keydown', 'touchstart'].forEach(evt => { window.addEventListener(evt, () => { window.scapeWebAudio.ensureCtx(); diff --git a/src/main/webapp/sw.js b/src/main/webapp/sw.js index 4ce1e8a..e0e1072 100644 --- a/src/main/webapp/sw.js +++ b/src/main/webapp/sw.js @@ -1,4 +1,4 @@ -const CACHE_VERSION = '2006scape-web-v5'; +const CACHE_VERSION = '2006scape-web-v6'; const SHELL_ASSETS = [ './', 'index.html',