// Audio: an AudioContext shared by the rendered-buffer playback (the simulation, the reference // renders) and a spessasynth_lib worklet synth for playing SoundFonts live from the keyboard and // MIDI (the SF2 built here, or the reference SF2). import { WorkletSynthesizer } from "spessasynth_lib"; import processorUrl from "spessasynth_lib/dist/spessasynth_processor.min.js?url"; export class Audio { ctx: AudioContext | null = null; synth: WorkletSynthesizer | null = null; private master: GainNode | null = null; private starting: Promise | null = null; private bankKey = ""; private current: AudioBufferSourceNode | null = null; volume = 0.8; start(): Promise { if (this.ctx && this.ctx.state === "suspended") void this.ctx.resume(); if (!this.starting) { this.starting = (async () => { const ctx = new AudioContext({ latencyHint: "interactive" }); this.ctx = ctx; void ctx.resume(); this.master = ctx.createGain(); this.master.gain.value = this.volume; this.master.connect(ctx.destination); await ctx.audioWorklet.addModule(processorUrl); const synth = new WorkletSynthesizer(ctx); synth.connect(this.master); await synth.isReady; this.synth = synth; })(); } return this.starting; } setVolume(v: number) { this.volume = v; if (this.master) this.master.gain.value = v; } /** play a mono buffer (stops the previous one); resolves when it ends */ async play(x: Float32Array, fs: number, gain = 1): Promise { await this.start(); this.stop(); const ctx = this.ctx!; const buf = ctx.createBuffer(1, Math.max(1, x.length), fs); const y = new Float32Array(x.length); for (let i = 0; i < x.length; i++) y[i] = x[i] * gain; buf.copyToChannel(y, 0); const src = ctx.createBufferSource(); src.buffer = buf; src.connect(this.master!); this.current = src; return new Promise((res) => { src.onended = () => { if (this.current === src) this.current = null; res(); }; src.start(); }); } stop() { try { this.current?.stop(); } catch { /* already stopped */ } this.current = null; } /** load a SoundFont into the live synth (key: to avoid reloading the same one) and select a preset */ async loadBank(key: string, data: ArrayBuffer, bank: number, program: number): Promise { await this.start(); const s = this.synth!; if (this.bankKey !== key) { s.stopAll(true); await s.soundBankManager.addSoundBank(data.slice(0), "main"); this.bankKey = key; } s.controllerChange(0, 0 as never, bank & 0x7f); s.controllerChange(0, 32 as never, 0); s.programChange(0, program); s.controllerChange(0, 91 as never, 30); } noteOn(note: number, vel: number) { this.synth?.noteOn(0, note, Math.max(1, Math.min(127, Math.round(vel)))); } noteOff(note: number) { this.synth?.noteOff(0, note); } sustain(on: boolean) { this.synth?.controllerChange(0, 64 as never, on ? 127 : 0); } }