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): retain mini-game playback intent during device suspension
yhh56674bb9e917
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cf46aa793..62518afe1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Mini-game audio keeps playback ownership through device suspension.** Device-paused voices remain live for AudioSource completion, bus gain updates, and priority budgets. New play requests and manual resumes wait for device recovery; manual pauses withdraw automatic recovery, while stopped or despawned voices never restart.+- **Async Box2D systems retain their physics performance category.** Physics stepping, interpolation, contact event delivery, and character controllers now appear under physics after module loading completes. Deferred system registration can explicitly provide its profiling domain without changing the classification of later registrations.- **Box2D initialization and shutdown belong to their App.** Stopping an App before its module finishes loading prevents late physics initialization and system installation. Shared plugin instances keep independent bridges and module ownership, so an older App cannot shut down or replace a newer App's physics world; cancelled load failures do not change the stopped App's subsystem status.diff --git a/sdk/src/audio/MiniGameAudioBackend.ts b/sdk/src/audio/MiniGameAudioBackend.tsindex 400778dbc..5a225d54e 100644--- a/sdk/src/audio/MiniGameAudioBackend.ts+++ b/sdk/src/audio/MiniGameAudioBackend.ts@@ -17,6 +17,11 @@ import type { MiniGameGlobal, MiniGameInnerAudioContext } from '../platform/miniimport { scalar } from '../math/scalar';import { log } from '../util/logger';+interface MiniGameAudioDeviceState {+ suspended: boolean;+ pending: Map<number, MiniGameInnerAudioContext>;+}+class MiniGameAudioHandle implements AudioHandle {readonly id: number;onEnd?: () => void;@@ -25,7 +30,8 @@ class MiniGameAudioHandle implements AudioHandle {private contexts_: Map<number, MiniGameInnerAudioContext>;private done_ = false;- constructor(id: number, ctx: MiniGameInnerAudioContext, contexts: Map<number, MiniGameInnerAudioContext>) {+ constructor(id: number, ctx: MiniGameInnerAudioContext, contexts: Map<number, MiniGameInnerAudioContext>,+ private readonly device_: MiniGameAudioDeviceState) {this.id = id;this.ctx_ = ctx;this.contexts_ = contexts;@@ -41,6 +47,7 @@ class MiniGameAudioHandle implements AudioHandle {if (!this.isLive_()) return;this.done_ = true;this.contexts_.delete(this.id);+ this.device_.pending.delete(this.id);try {if (alsoStop) this.ctx_.stop();} finally {@@ -61,12 +68,14 @@ class MiniGameAudioHandle implements AudioHandle {pause(): void {if (!this.isLive_()) return;+ this.device_.pending.delete(this.id);this.ctx_.pause();}resume(): void {if (!this.isLive_()) return;- this.ctx_.play();+ if (this.device_.suspended) this.device_.pending.set(this.id, this.ctx_);+ else this.ctx_.play();}setVolume(volume: number): void {@@ -97,7 +106,8 @@ class MiniGameAudioHandle implements AudioHandle {}get isPlaying(): boolean {- return this.isLive_() && !this.ctx_.paused;+ // Device suspension preserves playback intent, like a suspended WebAudio context.+ return this.isLive_() && (!this.ctx_.paused || this.device_.pending.get(this.id) === this.ctx_);}get currentTime(): number {@@ -116,7 +126,7 @@ export class MiniGameAudioBackend implements PlatformAudioBackend {private readonly g_: MiniGameGlobal;private contexts_ = new Map<number, MiniGameInnerAudioContext>();- private suspendedContexts_: Map<number, MiniGameInnerAudioContext> | null = null;+ private readonly device_: MiniGameAudioDeviceState = { suspended: false, pending: new Map() };private urlCache_ = new Map<number, string>();private nextId_ = 0;@@ -173,42 +183,43 @@ export class MiniGameAudioBackend implements PlatformAudioBackend {const handleId = ++this.nextId_;this.contexts_.set(handleId, ctx);- const handle = new MiniGameAudioHandle(handleId, ctx, this.contexts_);+ const handle = new MiniGameAudioHandle(handleId, ctx, this.contexts_, this.device_);ctx.onEnded(() => handle.onNaturalEnd());ctx.onError((res) => {log.error('audio', `Playback error for "${url}"`, res.errMsg);});ctx.src = url;- ctx.play();+ handle.resume();return handle;}suspend(): void {- if (this.suspendedContexts_) return;- const suspended = new Map<number, MiniGameInnerAudioContext>();- this.suspendedContexts_ = suspended;+ if (this.device_.suspended) return;+ this.device_.suspended = true;for (const [id, ctx] of this.contexts_) {if (ctx.paused) continue;- suspended.set(id, ctx);+ this.device_.pending.set(id, ctx);ctx.pause();}}resume(): void {- const suspended = this.suspendedContexts_;- if (!suspended) return;- this.suspendedContexts_ = null;- for (const [id, ctx] of suspended) {+ if (!this.device_.suspended) return;+ this.device_.suspended = false;+ for (const [id, ctx] of this.device_.pending) {+ this.device_.pending.delete(id);if (this.contexts_.get(id) === ctx && ctx.paused) {ctx.play();}+ if (this.device_.suspended) break;}}dispose(): void {- this.suspendedContexts_ = null;+ this.device_.suspended = false;+ this.device_.pending.clear();for (const ctx of this.contexts_.values()) {ctx.destroy();}diff --git a/sdk/tests/audio-minigame-source-suspension.test.ts b/sdk/tests/audio-minigame-source-suspension.test.tsnew file mode 100644index 000000000..4b014261f--- /dev/null+++ b/sdk/tests/audio-minigame-source-suspension.test.ts@@ -0,0 +1,55 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, expect, it, vi } from 'vitest';+import { MiniGameAudioBackend } from '../src/audio/MiniGameAudioBackend';+import type { MiniGameGlobal, MiniGameInnerAudioContext } from '../src/platform/minigame/api';++const contexts: ReturnType<typeof context>[] = [];+function context() {+ const ctx = { src: '', startTime: 0, loop: false, volume: 1, playbackRate: 1, paused: true,+ currentTime: 0, duration: 1, obeyMuteSwitch: false, ended: () => {},+ play: vi.fn(() => { ctx.paused = false; }), pause: vi.fn(() => { ctx.paused = true; }),+ stop: vi.fn(() => { ctx.paused = true; }), destroy: vi.fn(() => { ctx.paused = true; }),+ onEnded: vi.fn((fn: () => void) => { ctx.ended = fn; }), onError: vi.fn() };+ return ctx;+}+vi.mock('../src/platform/base', async original => ({+ ...await original<typeof import('../src/platform/base')>(),+ platformCreateAudioBackend: () => new MiniGameAudioBackend({+ createInnerAudioContext: () => {+ const ctx = context(); contexts.push(ctx); return ctx as unknown as MiniGameInnerAudioContext;+ },+ } as unknown as MiniGameGlobal),+ platformOnMemoryWarning: () => () => {},+}));+const { App } = await import('../src/app/app');+const { AudioPlugin } = await import('../src/audio/AudioPlugin');+const { Audio } = await import('../src/audio/Audio');+const { AudioSource } = await import('../src/audio/AudioComponents');+const apps: ReturnType<typeof App.new>[] = [];+afterEach(() => { for (const app of apps.splice(0)) app.quit(); contexts.length = 0; });+async function scene() {+ const app = App.new().addPlugin(new AudioPlugin()); apps.push(app);+ const audio = app.getResource(Audio); await audio.preload('loop.wav');+ const entity = app.world.spawn(); app.world.insert(entity, AudioSource, { clip: 'loop.wav', playing: true, volume: .8 });+ await app.tick(1 / 60); return { app, audio, entity };+}+it('ticks during device suspension retain source state, budget and bus ownership', async () => {+ const { app, audio, entity } = await scene(); audio.setMaxVoices(1); audio.suspend();+ for (let i = 0; i < 20; i++) await app.tick(1 / 60);+ expect(app.world.get(entity, AudioSource).playing).toBe(true);+ expect(app.world.get(entity, AudioSource).finished).toBe(false);+ audio.setSFXVolume(.5);+ expect(audio.playSFX('loop.wav', { priority: -1 })?.isPlaying).toBe(false);+ audio.resume(); await app.tick(1 / 60); audio.setSFXVolume(.25);+ expect(contexts).toHaveLength(1); expect(contexts[0].volume).toBeCloseTo(.2);+ expect(contexts[0].play).toHaveBeenCalledTimes(2);+ contexts[0].ended(); await app.tick(1 / 60);+ expect(app.world.get(entity, AudioSource).finished).toBe(true);+});+it('despawning a suspended source retires its context without automatic restart', async () => {+ const { app, audio, entity } = await scene(); const ctx = contexts[0];+ audio.suspend(); app.world.despawn(entity); audio.resume(); await app.tick(1 / 60);+ expect(ctx.stop).toHaveBeenCalledOnce(); expect(ctx.destroy).toHaveBeenCalledOnce();+ expect(ctx.play).toHaveBeenCalledOnce();+});diff --git a/sdk/tests/minigame-audio-backend.test.ts b/sdk/tests/minigame-audio-backend.test.tsindex 5c780e420..1e5798df1 100644--- a/sdk/tests/minigame-audio-backend.test.ts+++ b/sdk/tests/minigame-audio-backend.test.ts@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { describe, it, expect, beforeEach, vi } from 'vitest';import { MiniGameAudioBackend } from '../src/audio/MiniGameAudioBackend';+import { AudioAPI } from '../src/audio/Audio';function createMockInnerAudioContext() {const ctx = {@@ -139,6 +140,56 @@ describe('MiniGameAudioBackend', () => {});describe('suspend/resume', () => {+ it('keeps device-paused voices logically playing for source and budget tracking', async () => {+ const audio = new AudioAPI(backend, null), buffer = await backend.loadBuffer('a.mp3');+ audio.setMaxVoices(1);+ const voice = audio.playBuffer(buffer, { priority: 9, volume: .8 });+ const ctx = (globalThis as any).wx.createInnerAudioContext.mock.results[0].value;+ audio.suspend();+ expect(ctx.paused).toBe(true); expect(voice.isPlaying).toBe(true);+ audio.setSFXVolume(.5);+ expect(audio.playBuffer(buffer, { priority: 1 }).isPlaying).toBe(false);+ audio.resume(); audio.setSFXVolume(.25);+ expect(ctx.volume).toBeCloseTo(.2); expect(ctx.play).toHaveBeenCalledTimes(2);+ });+ it('defers a new voice until device resume', async () => {+ const buffer = await backend.loadBuffer('a.mp3'); backend.suspend();+ const voice = backend.play(buffer, {});+ const ctx = (globalThis as any).wx.createInnerAudioContext.mock.results[0].value;+ expect(ctx.play).not.toHaveBeenCalled(); expect(voice.isPlaying).toBe(true);+ backend.resume(); expect(ctx.play).toHaveBeenCalledOnce();+ });+ it('a manual pause during device suspension withdraws automatic resume', async () => {+ const buffer = await backend.loadBuffer('a.mp3'), voice = backend.play(buffer, {});+ backend.suspend(); voice.pause(); backend.resume();+ expect(voice.isPlaying).toBe(false);+ const ctx = (globalThis as any).wx.createInnerAudioContext.mock.results[0].value;+ expect(ctx.play).toHaveBeenCalledOnce();+ });+ it('a manual resume during device suspension queues playback', async () => {+ const buffer = await backend.loadBuffer('a.mp3'), voice = backend.play(buffer, {});+ voice.pause(); backend.suspend(); voice.resume();+ const ctx = (globalThis as any).wx.createInnerAudioContext.mock.results[0].value;+ expect(ctx.paused).toBe(true); expect(ctx.play).toHaveBeenCalledOnce();+ backend.resume(); expect(voice.isPlaying).toBe(true); expect(ctx.play).toHaveBeenCalledTimes(2);+ });+ it('a host playback callback can withdraw another queued voice before it resumes', async () => {+ const buffer = await backend.loadBuffer('a.mp3');+ backend.play(buffer, {}); const second = backend.play(buffer, {}); backend.suspend();+ const contexts = (globalThis as any).wx.createInnerAudioContext.mock.results;+ contexts[0].value.play.mockImplementation(() => { contexts[0].value.paused = false; second.pause(); });+ backend.resume();+ expect(second.isPlaying).toBe(false); expect(contexts[1].value.play).toHaveBeenCalledOnce();+ });+ it('stopping a suspended managed voice frees its budget and prevents later playback', async () => {+ const audio = new AudioAPI(backend, null), buffer = await backend.loadBuffer('a.mp3');+ audio.setMaxVoices(1); const old = audio.playBuffer(buffer, { priority: 9 });+ audio.suspend(); old.stop();+ const next = audio.playBuffer(buffer, { priority: 1 });+ audio.resume(); expect(old.isPlaying).toBe(false); expect(next.isPlaying).toBe(true);+ const contexts = (globalThis as any).wx.createInnerAudioContext.mock.results;+ expect(contexts[0].value.play).toHaveBeenCalledOnce(); expect(contexts[1].value.play).toHaveBeenCalledOnce();+ });it('resumes device-paused voices while preserving a manually paused voice', async () => {const buffer = await backend.loadBuffer('a.mp3');const manual = backend.play(buffer, {}), active = backend.play(buffer, {});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 4e9017e9a..750dc6d4c 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): retain mini-game playback intent during device suspension':+ { note: 'Mini-game audio keeps playback ownership through device suspension.' },'fix(profiling): attribute async Box2D systems to physics':{ note: 'Async Box2D systems retain their physics performance category.' },'fix(physics): isolate async Box2D module ownership by app':