A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(audio): share native completion events across backend subscribers
yhhd1b6d3543fbd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ef38808f4..f5532f149 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Native audio completion subscriptions are independent.** Multiple backends sharing one host bridge receive their own voice-end notifications, and preview shutdowns withdraw only their subscription. Dispatch skips listeners withdrawn during the event, defers new listeners to the next event, and notifies remaining listeners before propagating the first callback error.+- **Mini-game and native audio completion retires ownership before callbacks.** Natural completion releases the player or voice record before calling user code, so callback exceptions and repeated end notifications cannot retain resources or deliver completion twice. Stopped, ended, and backend-disposed mini-game handles ignore later playback and parameter operations; retired native handles also stop sending host operations.- **Audio device suspension freezes volume fades.** Fade elapsed time stays at its current position while the device is suspended, preventing covered or interrupted playback from completing a fade-out before resume. Existing per-voice pause handling remains effective after the device resumes.diff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.tsindex 8fc1d81b9..14c349877 100644--- a/sdk/src/platform/native/hostBridge.ts+++ b/sdk/src/platform/native/hostBridge.ts@@ -349,14 +349,24 @@ function hostFetch(* Assemble the audio bridge from the host's es_audio* primitives, or undefined* when the host bound none (→ silent Null backend). Also installs* `es_onNativeAudioEnded`, the entry point the host calls when a voice ends on- * its own, fanning out to the backend that subscribed.+ * its own, fanning out to the subscribed backends.*/function hostAudio(bindings: NativeHostBindings, scope: Record<string, unknown>,): NativeAudioBridge | undefined {if (!hasAudioBindings(scope)) return undefined;- let ended: ((voiceId: number) => void) | null = null;- scope.es_onNativeAudioEnded = (voiceId: number): void => { ended?.(voiceId); };+ let ended: Array<{ callback: (voiceId: number) => void; active: boolean }> = [];+ scope.es_onNativeAudioEnded = (voiceId: number): void => {+ let failed = false;+ let failure: unknown;+ for (const subscription of ended) {+ if (!subscription.active) continue;+ try { subscription.callback(voiceId); } catch (error) {+ if (!failed) { failed = true; failure = error; }+ }+ }+ if (failed) throw failure;+ };return {load: (bytes) => bindings.es_audioLoad!(bytes),unload: (id) => bindings.es_audioUnload!(id),@@ -371,7 +381,15 @@ function hostAudio(voiceState: (v) => bindings.es_audioVoiceState!(v),suspendAll: () => bindings.es_audioSuspendAll!(),resumeAll: () => bindings.es_audioResumeAll!(),- onEnded: (cb) => { ended = cb; return () => { if (ended === cb) ended = null; }; },+ onEnded: (callback) => {+ const subscription = { callback, active: true };+ ended = [...ended, subscription];+ return () => {+ if (!subscription.active) return;+ subscription.active = false;+ ended = ended.filter(entry => entry !== subscription);+ };+ },// Optional: a host without the analyser tap simply has no spectrum, and// a visualizer falls back to flat bars (as it does on any backend// without analysis).diff --git a/sdk/tests/native-audio.test.ts b/sdk/tests/native-audio.test.tsindex b07ed60bf..ae31dc60a 100644--- a/sdk/tests/native-audio.test.ts+++ b/sdk/tests/native-audio.test.ts@@ -77,6 +77,34 @@ describe('hasAudioBindings', () => {});describe('createHostBridge — audio assembly', () => {+ it('keeps independent subscriptions when the same callback is registered twice', () => {+ const scope = audioScope(), audio = createHostBridge(scope).audio!, callback = vi.fn();+ const first = audio.onEnded(callback), second = audio.onEnded(callback);+ const push = scope.es_onNativeAudioEnded as (id: number) => void;+ push(100); expect(callback).toHaveBeenCalledTimes(2);+ first(); first(); callback.mockClear(); push(101); expect(callback).toHaveBeenCalledOnce();+ second(); callback.mockClear(); push(102); expect(callback).not.toHaveBeenCalled();+ });+ it('continues notifying other subscribers when one callback throws', () => {+ const scope = audioScope(), audio = createHostBridge(scope).audio!, second = vi.fn();+ audio.onEnded(() => { throw Error('subscriber failed'); }); audio.onEnded(second);+ expect(() => (scope.es_onNativeAudioEnded as (id: number) => void)(100)).toThrow('subscriber failed');+ expect(second).toHaveBeenCalledWith(100);+ });+ it('a subscription withdrawn during dispatch cannot receive that event', () => {+ const scope = audioScope(), audio = createHostBridge(scope).audio!, second = vi.fn();+ let release = () => {};+ audio.onEnded(() => release()); release = audio.onEnded(second);+ (scope.es_onNativeAudioEnded as (id: number) => void)(100);+ expect(second).not.toHaveBeenCalled();+ });+ it('subscriptions added during dispatch wait for the next completion', () => {+ const scope = audioScope(), audio = createHostBridge(scope).audio!, added = vi.fn();+ let installed = false;+ audio.onEnded(() => { if (!installed) { installed = true; audio.onEnded(added); } });+ const push = scope.es_onNativeAudioEnded as (id: number) => void;+ push(100); expect(added).not.toHaveBeenCalled(); push(101); expect(added).toHaveBeenCalledWith(101);+ });it('assembles bridge.audio when the host bound the engine', () => {expect(createHostBridge(audioScope()).audio).toBeDefined();});@@ -92,6 +120,23 @@ describe('createHostBridge — audio assembly', () => {});describe('NativeAudioBackend', () => {+ it('two backends sharing one native bridge receive their own voice completions', () => {+ const scope = audioScope(), audio = createHostBridge(scope).audio!;+ const first = new NativeAudioBackend(audio), second = new NativeAudioBackend(audio);+ const a = first.play({ id: 1, duration: 1 }, {}), b = second.play({ id: 1, duration: 1 }, {});+ a.onEnd = vi.fn(); b.onEnd = vi.fn();+ const push = scope.es_onNativeAudioEnded as (id: number) => void;+ push(a.id); expect(a.onEnd).toHaveBeenCalledOnce(); expect(b.onEnd).not.toHaveBeenCalled();+ first.dispose(); push(b.id); expect(b.onEnd).toHaveBeenCalledOnce(); second.dispose();+ });+ it('repeated preview backend shutdowns preserve the main backend completion subscription', () => {+ const scope = audioScope(), audio = createHostBridge(scope).audio!;+ const main = new NativeAudioBackend(audio), handle = main.play({ id: 1, duration: 1 }, {});+ handle.onEnd = vi.fn();+ for (let i = 0; i < 100; i++) new NativeAudioBackend(audio).dispose();+ (scope.es_onNativeAudioEnded as (id: number) => void)(handle.id);+ expect(handle.onEnd).toHaveBeenCalledOnce(); main.dispose();+ });it('loads, plays and reports state through the bridge', async () => {const scope = audioScope();const host = installAudioHost(scope); // capture the same closure the bridge will usediff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 7a79382fc..54e18f8a4 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(audio): share native completion events across backend subscribers':+ { note: 'Native audio completion subscriptions are independent.' },'fix(audio): retire platform handles before completion callbacks':{ note: 'Mini-game and native audio completion retires ownership before callbacks.' },'fix(audio): freeze fade clocks during device suspension':