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): preserve latest BGM intent across loading
yhh0e352e5e1b75
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0661bd04b..62bf4e85a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **BGM playback follows the latest request instead of load completion order.** New requests and stop commands invalidate older pending starts, including when the replacement is already cached. An immediate stop also ends a track already fading out, while repeated positive fade-out requests preserve the existing ramp. Loaded buffers remain available for later playback.+- **Web audio loads cannot cross disposed or replaced contexts.** Async reads and decodes capture their context generation and validate it before decoding or publishing a buffer. Late work rejects without borrowing a new session's cached handle, replacing its source entry or repopulating disposed storage; current-session loads and same-session source revisions retain their existing behavior.- **Web audio source records follow live buffer ownership.** URL cache entries and invalidation identities retire after their current buffer and pending loads are released, instead of retaining every historical scene path. Distinct source records preserve overlapping invalidated loads, and unloading an older result leaves the replacement cached; failed loads release their records too.diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.tsindex 4c0f6de35..dad8f1471 100644--- a/sdk/src/audio/Audio.ts+++ b/sdk/src/audio/Audio.ts@@ -106,6 +106,7 @@ export class AudioAPI {private residentBytes_ = 0;private bufferBudgetOverride_: number | null = null;private bgmHandle_: AudioHandle | null = null;+ private bgmRequest_ = 0;private bgmVolume_ = 1.0;/** Volume ramps in flight, advanced by {@link updateFades} from the frame* loop — NOT by requestAnimationFrame, which is a browser global a device@@ -416,7 +417,9 @@ export class AudioAPI {fadeIn?: number;crossFade?: number;}): void {+ const request = ++this.bgmRequest_;const play = (buffer: AudioBufferHandle) => {+ if (this.disposed_ || request !== this.bgmRequest_) return;this.cancelFades_();const targetVolume = config?.volume ?? 1.0;@@ -458,6 +461,7 @@ export class AudioAPI {}stopAll(): void {+ this.bgmRequest_++;this.cancelFades_();if (this.bgmHandle_) {this.bgmHandle_.stop();@@ -466,7 +470,11 @@ export class AudioAPI {}stopBGM(fadeOut?: number): void {- if (!this.bgmHandle_) return;+ this.bgmRequest_++;+ if (!this.bgmHandle_) {+ if (!(fadeOut && fadeOut > 0)) this.cancelFades_();+ return;+ }this.cancelFades_();if (fadeOut && fadeOut > 0) {const handle = this.bgmHandle_;diff --git a/sdk/tests/audio-play-intent.test.ts b/sdk/tests/audio-play-intent.test.tsnew file mode 100644index 000000000..036be20fe--- /dev/null+++ b/sdk/tests/audio-play-intent.test.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { beforeEach, expect, it, vi } from 'vitest';+import { AudioAPI } from '../src/audio/Audio';+import type { AudioBufferHandle, AudioHandle, PlatformAudioBackend, PlayConfig } from '../src/audio/PlatformAudioBackend';++const loads = new Map<string, (buffer: AudioBufferHandle) => void>();+function voice(id: number): AudioHandle {+ let playing = true;+ return {+ id, stop: vi.fn(() => { playing = false; }), pause: vi.fn(() => { playing = false; }),+ resume: vi.fn(() => { playing = true; }),+ setVolume: vi.fn(), setPan: vi.fn(), setLoop: vi.fn(), setPlaybackRate: vi.fn(),+ get isPlaying() { return playing; }, currentTime: 0, duration: 1,+ };+}+function create() {+ let nextVoice = 0;+ const backend = {+ name: 'intent-test', delivery: 'bytes', mixer: null, isReady: true,+ initialize: vi.fn(async () => {}), ensureResumed: vi.fn(async () => {}),+ loadBuffer: vi.fn((url: string) => new Promise<AudioBufferHandle>(resolve => { loads.set(url, resolve); })),+ loadBufferFromData: vi.fn(async () => ({ id: 1, duration: 1 })),+ unloadBuffer: vi.fn(), play: vi.fn((_buffer: AudioBufferHandle, _config: PlayConfig) => voice(++nextVoice)),+ suspend: vi.fn(), resume: vi.fn(), dispose: vi.fn(),+ } satisfies PlatformAudioBackend;+ return { backend, audio: new AudioAPI(backend) };+}+beforeEach(() => loads.clear());+async function finish(audio: AudioAPI, url: string, id: number) {+ loads.get(url)!({ id, duration: 1 });+ await vi.waitFor(() => expect(audio.getBufferHandle(url)?.id).toBe(id));+}++it.each(['old-first', 'new-first'] as const)('only starts the latest BGM request when loads finish %s', async order => {+ const { audio, backend } = create();+ audio.playBGM('old.wav');+ audio.playBGM('new.wav');+ if (order === 'old-first') { await finish(audio, 'old.wav', 1); await finish(audio, 'new.wav', 2); }+ else { await finish(audio, 'new.wav', 2); await finish(audio, 'old.wav', 1); }+ expect(backend.play).toHaveBeenCalledTimes(1);+ expect(backend.play).toHaveBeenCalledWith(expect.objectContaining({ id: 2 }), expect.objectContaining({ bus: 'music' }));+});++it.each(['stopBGM', 'stopAll'] as const)('%s cancels a BGM request before it has a voice', async stop => {+ const { audio, backend } = create();+ audio.playBGM('pending.wav');+ audio[stop]();+ await finish(audio, 'pending.wav', 1);+ expect(backend.play).not.toHaveBeenCalled();+});++it('keeps a cached BGM ahead of an earlier pending request', async () => {+ const { audio, backend } = create();+ await audio.preloadFromData('ready.wav', new ArrayBuffer(8));+ audio.playBGM('pending.wav');+ audio.playBGM('ready.wav');+ await finish(audio, 'pending.wav', 9);+ expect(backend.play).toHaveBeenCalledTimes(1);+ expect(backend.play.mock.calls[0][0].id).toBe(1);+});++it.each([false, true])('an immediate stop ends outgoing BGM while repeated fade requests remain idempotent (repeat=%s)', async repeat => {+ const { audio, backend } = create();+ await audio.preloadFromData('ready.wav', new ArrayBuffer(8));+ audio.playBGM('ready.wav');+ const handle = backend.play.mock.results[0].value;+ audio.stopBGM(1);+ if (repeat) {+ audio.stopBGM(1);+ expect(handle.isPlaying).toBe(true);+ }+ audio.stopBGM();+ expect(handle.isPlaying).toBe(false);+ expect(handle.stop).toHaveBeenCalledOnce();+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 999641b1b..0716c6364 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): preserve latest BGM intent across loading':+ { note: 'BGM playback follows the latest request instead of load completion order.' },'fix(audio): reject loads from retired context generations':{ note: 'Web audio loads cannot cross disposed or replaced contexts.' },'fix(audio): retire source records with owned buffers':