feat(web-audio): implement Class56 MIDI player with FluidSynth and TimGM6mb.sf2

Enables authentic General MIDI music playback in `2006Scape-Web` over both HTTP and HTTPS by implementing the missing `Class56_Sub1_Sub1` web adapter and wiring `js-synthesizer` (`libfluidsynth-2.3.0.js`) with the `TimGM6mb.sf2` SoundFont.

### Java MIDI Pipeline Bridge
- `Class56_Sub1_Sub1.java`:
  - Added `org.scape2006.web` implementation of `Class56` forwarding `method827`, `method828`, `method830`, `method831`, `method832`, and `method833` to `DesktopHooks.playMidiBytes`, `setSignlinkVolume`, and `stopSignlinkMidi`.
- `build.gradle`:
  - Patched `Game.constructMusic()` in `syncSharedSources` to instantiate `new Class56_Sub1_Sub1()` directly instead of `Class.forName("Class56_Sub1_Sub1").newInstance()`, preventing `musicIsntNull()` from returning `false`.

### FluidSynth Web Audio & Caching
- `src/main/webapp/libfluidsynth-2.3.0.js`, `js-synthesizer.min.js`, `TimGM6mb.sf2`:
  - Bundled FluidSynth WASM/JS synthesizer and General MIDI SoundFont (`5.8M`) locally for offline and plain-HTTP LAN compatibility.
- `src/main/webapp/index.html`:
  - Wired `window.scapeWebAudio` (`ensureFluidSynth`, `playMidi`, `setMidiVolume`, `stopMidi`) to load `TimGM6mb.sf2`, loop tracks via `setPlayerLoop(-1)`, and resume pending MIDI on first user gesture.
- `src/main/webapp/sw.js`:
  - Added `libfluidsynth-2.3.0.js`, `js-synthesizer.min.js`, and `TimGM6mb.sf2` to `SHELL_ASSETS` and bumped `CACHE_VERSION` to `2006scape-web-v5`.
This commit is contained in:
Dark98 committed 2026-12-01 14:53:04 +00:00
1 parent 4bcb91c3a2
commit 02c3d8fb10
7 files changed
+164 -15

No files matched your search

+1
View File
@@ -56,6 +56,7 @@ def syncSharedSources = tasks.register('syncSharedSources') {
src = src.replace('java.net.InetSocketAddress', 'org.scape2006.web.net.InetSocketAddress') src = src.replace('java.net.InetSocketAddress', 'org.scape2006.web.net.InetSocketAddress')
if (element.name == 'Game.java') { if (element.name == 'Game.java') {
src = src.replace('Signlink.reporterror("glfc_ex "', 'Signlink.reporterror("glfc_ex " + _ex + " | "') src = src.replace('Signlink.reporterror("glfc_ex "', 'Signlink.reporterror("glfc_ex " + _ex + " | "')
src = src.replace('(Class56) Class.forName("Class56_Sub1_Sub1").newInstance()', 'new Class56_Sub1_Sub1()')
} }
dest.text = "package org.scape2006.web;\n" + src dest.text = "package org.scape2006.web;\n" + src
} }
@@ -0,0 +1,44 @@
package org.scape2006.web;
/**
* Web MIDI player implementation of Class56, bridging Game's music pipeline
* to DesktopHooks / window.scapeWebAudio (WebAudioTinySynth).
*/
public final class Class56_Sub1_Sub1 extends Class56 {
@Override
void method827(int volume, byte[] midiBytes, int unused, boolean loop) {
if (midiBytes != null && midiBytes.length > 0) {
DesktopHooks.playMidiBytes(midiBytes, volume);
} else {
DesktopHooks.stopSignlinkMidi();
}
}
@Override
void method828() {
DesktopHooks.stopSignlinkMidi();
}
@Override
void method830(int volume, int fade) {
DesktopHooks.setSignlinkVolume(volume);
}
@Override
void method831(int volume) {
DesktopHooks.setSignlinkVolume(volume);
}
@Override
void method832(int i) {
if (i > -90) {
DesktopHooks.stopSignlinkMidi();
}
}
@Override
void method833() {
DesktopHooks.stopSignlinkMidi();
}
}
Binary file not shown.
+82 -13
View File
@@ -419,22 +419,67 @@
</div> </div>
<!-- Web Audio + Cache Preloader (must run synchronously before client.js main()) --> <!-- Web Audio + Cache Preloader (must run synchronously before client.js main()) -->
<script src="libfluidsynth-2.3.0.js"></script>
<script src="js-synthesizer.min.js"></script>
<script> <script>
window.scapeWebAudio = { window.scapeWebAudio = {
ctx: null, ctx: null,
midiGain: 0.7, midiGain: 0.7,
synth: null, synth: null,
sequencer: null, synthNode: null,
synthLoading: null,
synthReady: false,
pendingMidi: null,
ensureCtx() { ensureCtx() {
if (!this.ctx) { if (!this.ctx) {
const AudioCtx = window.AudioContext || window.webkitAudioContext; const AudioCtx = window.AudioContext || window.webkitAudioContext;
if (AudioCtx) this.ctx = new AudioCtx(); if (AudioCtx) this.ctx = new AudioCtx();
} }
if (this.ctx && this.ctx.state === 'suspended') { if (this.ctx && this.ctx.state === 'suspended') {
this.ctx.resume().catch(() => {}); this.ctx.resume().then(() => {
if (this.pendingMidi && this.synthReady && this.ctx && this.ctx.state === 'running') {
const pending = this.pendingMidi;
this.pendingMidi = null;
this.playMidi(pending, this.midiGain);
}
}).catch(() => {});
} }
return this.ctx; return this.ctx;
}, },
ensureFluidSynth() {
if (this.synthReady) return Promise.resolve(this.synth);
if (this.synthLoading) return this.synthLoading;
const ctx = this.ensureCtx();
if (!ctx || typeof JSSynth === 'undefined') return Promise.resolve(null);
this.synthLoading = (async () => {
try {
await JSSynth.waitForReady();
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);
node.connect(ctx.destination);
this.synth = s;
this.synthNode = node;
this.synthReady = true;
if (this.pendingMidi && this.ctx && this.ctx.state === 'running') {
const pending = this.pendingMidi;
this.pendingMidi = null;
this.playMidi(pending, this.midiGain);
}
return s;
} catch (e) {
console.warn('FluidSynth init error:', e);
this.synthLoading = null;
return null;
}
})();
return this.synthLoading;
},
playPcm(bytes, volume) { playPcm(bytes, volume) {
const ctx = this.ensureCtx(); const ctx = this.ensureCtx();
if (!ctx || !bytes || bytes.length === 0) return; if (!ctx || !bytes || bytes.length === 0) return;
@@ -449,29 +494,53 @@
src.start(0); src.start(0);
}).catch(() => {}); }).catch(() => {});
}, },
playMidi(bytes, volume) { async playMidi(bytes, volume) {
this.midiGain = Math.max(0, Math.min(1, volume)); this.midiGain = Math.max(0, Math.min(1, volume));
if (this.sequencer && bytes && bytes.length > 0) { if (!bytes || bytes.length === 0) return;
try { this.ensureCtx();
this.sequencer.loadNewSongList([{ binary: new Uint8Array(bytes).buffer }]); if (!this.synthReady) {
this.sequencer.play(); this.pendingMidi = new Uint8Array(bytes);
} catch (e) { this.ensureFluidSynth();
console.warn('SpessaSynth MIDI playback error:', e); return;
}
if (this.ctx && this.ctx.state === 'suspended') {
this.pendingMidi = new Uint8Array(bytes);
return;
}
this.pendingMidi = null;
try {
const copy = new Uint8Array(bytes).buffer;
this.synth.setGain(this.midiGain * 0.5);
await this.synth.stopPlayer();
await this.synth.resetPlayer();
await this.synth.addSMFDataToPlayer(copy);
if (this.synth.setPlayerLoop) {
this.synth.setPlayerLoop(-1);
} }
await this.synth.playPlayer();
} catch (e) {
console.warn('FluidSynth MIDI playback error:', e);
} }
}, },
setMidiVolume(volume) { setMidiVolume(volume) {
this.midiGain = Math.max(0, Math.min(1, volume)); this.midiGain = Math.max(0, Math.min(1, volume));
if (this.synth && this.synth.setMasterGain) { if (this.synthReady && this.synth) {
this.synth.setMasterGain(this.midiGain); this.synth.setGain(this.midiGain * 0.5);
} }
}, },
stopMidi() { stopMidi() {
if (this.sequencer && this.sequencer.pause) { this.pendingMidi = null;
try { this.sequencer.pause(); } catch (_) {} if (this.synthReady && this.synth) {
try { this.synth.stopPlayer(); } catch (_) {}
} }
} }
}; };
['pointerdown', 'keydown', 'touchstart'].forEach(evt => {
window.addEventListener(evt, () => {
window.scapeWebAudio.ensureCtx();
window.scapeWebAudio.ensureFluidSynth();
}, { passive: true });
});
// Cache preloader (IndexedDB + HTTP fetch) // Cache preloader (IndexedDB + HTTP fetch)
window.scapePreloadCache = async function(cb) { window.scapePreloadCache = async function(cb) {
+31
View File
@@ -0,0 +1,31 @@
/*!
js-synthesizer version 1.13.0
@license
Copyright (C) 2026 jet
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["js-synthesizer"]=t():e.JSSynth=t()}(this,()=>(()=>{"use strict";var e={d:(t,s)=>{for(var n in s)e.o(s,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:s[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{AudioWorkletNodeSynthesizer:()=>Z,Constants:()=>s,LogLevel:()=>Q,MessageError:()=>C,SequencerEventTypes:()=>n,Synthesizer:()=>B,disableLogging:()=>X,restoreLogging:()=>Y,rewriteEventData:()=>k,version:()=>ee,waitForReady:()=>D});var s={};e.r(s),e.d(s,{PlayerSetTempoType:()=>i});var n={};e.r(n);const i={Internal:0,ExternalBpm:1,ExternalMidi:2};let r,_,l,a,o,h,u,d,c,y,g,f,m,p,v;function P(e){if(null!=e||!c){if(null!=e){if(!e.addFunction||!e.removeFunction||!e.addOnPostRun)throw new Error("Invalid 'module' object. libfluidsynth-*.js (2.4.6 or higher) must be used.");r=e,_=r.addFunction,l=r.removeFunction,o=r.addOnPostRun}else if("undefined"!=typeof AudioWorkletGlobalScope)r=AudioWorkletGlobalScope.wasmModule,_=r.addFunction||AudioWorkletGlobalScope.wasmAddFunction,l=r.removeFunction||AudioWorkletGlobalScope.wasmRemoveFunction,o=r.addOnPostRun||AudioWorkletGlobalScope.addOnPostRun;else{if("undefined"==typeof Module)throw new Error("wasm module is not available. libfluidsynth-*.js must be loaded.");r=Module,r.addFunction?(_=r.addFunction,l=r.removeFunction):(_=addFunction,l=removeFunction),o=r.addOnPostRun?r.addOnPostRun:"undefined"!=typeof addOnPostRun?addOnPostRun:void 0}a=r.FS,h=r.cwrap("fluid_settings_setint","number",["number","string","number"]),u=r.cwrap("fluid_settings_setnum","number",["number","string","number"]),d=r.cwrap("fluid_settings_setstr","number",["number","string","string"]),c=r.cwrap("fluid_synth_error","string",["number"]),y=r.cwrap("fluid_synth_sfload","number",["number","string","number"]),g=r.cwrap("fluid_sequencer_register_client","number",["number","string","number","number"]),f=r._malloc.bind(r),m=r._free.bind(r),p=r._fluid_synth_handle_midi_event.bind(r)}}const b=0;class w{constructor(e,t){this._ptr=e,this._module=t}getRaw(){return this._ptr}dispose(){this._ptr=b}getType(){return this._ptr===b?-1:this._module._fluid_event_get_type(this._ptr)}getSource(){return this._ptr===b?-1:this._module._fluid_event_get_source(this._ptr)}getDest(){return this._ptr===b?-1:this._module._fluid_event_get_dest(this._ptr)}getChannel(){return this._ptr===b?-1:this._module._fluid_event_get_channel(this._ptr)}getKey(){return this._ptr===b?-1:this._module._fluid_event_get_key(this._ptr)}getVelocity(){return this._ptr===b?-1:this._module._fluid_event_get_velocity(this._ptr)}getControl(){return this._ptr===b?-1:this._module._fluid_event_get_control(this._ptr)}getValue(){return this._ptr===b?-1:this._module._fluid_event_get_value(this._ptr)}getProgram(){return this._ptr===b?-1:this._module._fluid_event_get_program(this._ptr)}getData(){return this._ptr===b?-1:this._module._fluid_event_get_data(this._ptr)}getDuration(){return this._ptr===b?-1:this._module._fluid_event_get_duration(this._ptr)}getBank(){return this._ptr===b?-1:this._module._fluid_event_get_bank(this._ptr)}getPitch(){return this._ptr===b?-1:this._module._fluid_event_get_pitch(this._ptr)}getSFontId(){return this._ptr===b?-1:this._module._fluid_event_get_sfont_id(this._ptr)}}function S(e,t){switch(t.type){case 0:case"note":r._fluid_event_note(e,t.channel,t.key,t.vel,t.duration);break;case 1:case"noteon":case"note-on":r._fluid_event_noteon(e,t.channel,t.key,t.vel);break;case 2:case"noteoff":case"note-off":r._fluid_event_noteoff(e,t.channel,t.key);break;case 3:case"allsoundsoff":case"all-sounds-off":r._fluid_event_all_sounds_off(e,t.channel);break;case 4:case"allnotesoff":case"all-notes-off":r._fluid_event_all_notes_off(e,t.channel);break;case 5:case"bankselect":case"bank-select":r._fluid_event_bank_select(e,t.channel,t.bank);break;case 6:case"programchange":case"program-change":r._fluid_event_program_change(e,t.channel,t.preset);break;case 7:case"programselect":case"program-select":r._fluid_event_program_select(e,t.channel,t.sfontId,t.bank,t.preset);break;case 12:case"controlchange":case"control-change":r._fluid_event_control_change(e,t.channel,t.control,t.value);break;case 8:case"pitchbend":case"pitch-bend":r._fluid_event_pitch_bend(e,t.channel,t.value);break;case 9:case"pitchwheelsens":case"pitchwheelsensitivity":case"pitch-wheel-sens":case"pitch-wheel-sensitivity":r._fluid_event_pitch_wheelsens(e,t.channel,t.value);break;case 10:case"modulation":r._fluid_event_modulation(e,t.channel,t.value);break;case 11:case"sustain":r._fluid_event_sustain(e,t.channel,t.value);break;case 13:case"pan":r._fluid_event_pan(e,t.channel,t.value);break;case 14:case"volume":r._fluid_event_volume(e,t.channeLine truncated
//# sourceMappingURL=js-synthesizer.min.js.map
+1
View File
@@ -0,0 +1 @@
var Module=typeof Module!="undefined"?Module:{};var document=typeof document!=="undefined"?document:{};var window=typeof window!=="undefined"?window:{};if(typeof AudioWorkletGlobalScope!=="undefined"&&AudioWorkletGlobalScope){AudioWorkletGlobalScope.wasmModule=Module;AudioWorkletGlobalScope.wasmAddFunction=addFunction;AudioWorkletGlobalScope.wasmRemoveFunction=removeFunction;AudioWorkletGlobalScope.addOnPreRun=addOnPreRun;AudioWorkletGlobalScope.addOnInit=addOnInit;AudioWorkletGlobalScope.addOnPostRun=addOnPostRun}var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=(url=>{try{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText}catch(err){var data=tryParseAsDataURI(url);if(data){return intArrayToString(data)}throw err}});if(ENVIRONMENT_IS_WORKER){readBinary=(url=>{try{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}catch(err){var data=tryParseAsDataURI(url);if(data){return data}throw err}})}readAsync=((url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=(()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}var data=tryParseAsDataURI(url);if(data){onload(data.buffer);return}onerror()});xhr.onerror=onerror;xhr.send(null)})}setWindowTitle=(title=>document.title=title)}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];function uleb128Encode(n){if(n<128){return[n]}return[n%128|128,n>>7]}function convertJsFunctionToWasm(func,sig){if(typeof WebAssembly.Function=="function"){var typeNames={"i":"i32","j":"i64","f":"f32","d":"f64"};var type={parameters:[],results:sig[0]=="v"?[]:[typeNames[sig[0]]]};for(var i=1;i<sig.length;++i){type.parameters.push(typeNames[sig[i]])}return new WebAssembly.Function(type,func)}var typeSection=[1,96];var sigRet=sig.slice(0,1);var sigParam=sig.slice(1);var typeCodes={"i":127,"j":126,"f":125,"d":124};typeSection=typeSection.concat(uleb128Encode(sigParam.length));for(var i=0;i<sigParam.length;++i){typeSection.push(typeCodes[sigParam[i]])}if(sigRet=="v"){typeSection.push(0)}else{typeSection=typeSection.concat([1,typeCodes[sigRet]])}typeSection=[1].concat(uleb128Encode(typeSection.length),typeSection);var bytes=new Uint8Array([0,97,115,109,1,0,0,0].concat(typeSection,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0]));var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{"e":{"f":func}});var wrappedFunc=instance.exports["f"];return wrappedFunc}var freeTableIndexes=[];var functionsInTableMap;function getEmptyTableSlot(){if(freeTableIndexes.length){return freeTableIndexes.pop()}try{wasmTable.grow(1)}catch(err){if(!(err instanceof RangeError)){throw err}throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1}function updateTableMap(offset,count){for(var i=offset;i<offset+count;i++){var item=getWasmTableEntry(i);if(item){functionsInTableMap.set(item,i)}}}function addFunction(func,sig){if(!functionsInTableMap){functionsInTableMap=new WeakMap;updateTableMap(0,wasmTable.length)}if(functionsInTableMap.has(func)){return functionsInTableMap.get(func)}var ret=getEmptyTableSlot();try{setWasmTableEntry(ret,func)}catch(err){if(!(err instanceof TypeError)){throw err}var wrapped=convertJsFunctionToWasm(func,sig);setWasmTableEntry(ret,wrapped)}functionsInTableMap.set(func,ret);return ret}function removeFunction(index){functionsInTableMap.delete(getWasmTableEntry(index));freeTableIndexes.push(index)}var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}function getCFunc(ident){var func=Module["_"+ident];return func}function ccall(ident,returnType,argTypes,args,opts){var toC={"string":function(str){var ret=0;if(str!==nullLine truncated
+5 -2
View File
@@ -1,8 +1,11 @@
const CACHE_VERSION = '2006scape-web-v3'; const CACHE_VERSION = '2006scape-web-v5';
const SHELL_ASSETS = [ const SHELL_ASSETS = [
'./', './',
'index.html', 'index.html',
'manifest.webmanifest', 'manifest.webmanifest',
'libfluidsynth-2.3.0.js',
'js-synthesizer.min.js',
'TimGM6mb.sf2',
'js/client.js', 'js/client.js',
'hud_minimap_bezel.png', 'hud_minimap_bezel.png',
'hud_minimap_hole.png', 'hud_minimap_hole.png',
@@ -65,7 +68,7 @@ self.addEventListener('fetch', (event) => {
return; return;
} }
if (/\.(png|gif|jpg|jpeg|webp|svg|ico|css|webmanifest|dat|idx\d*)$/i.test(url.pathname)) { if (/\.(js|png|gif|jpg|jpeg|webp|svg|ico|css|webmanifest|dat|idx\d*|sf2|sf3|wasm)$/i.test(url.pathname)) {
event.respondWith((async () => { event.respondWith((async () => {
const cache = await caches.open(CACHE_VERSION); const cache = await caches.open(CACHE_VERSION);
const cached = await cache.match(req); const cached = await cache.match(req);