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): stop all owned voices and pending starts
yhhab005a2569e5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 62bf4e85a..b16a3cc31 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Stop All stops every owned audio voice and pending start.** Scripted effects, explicit tracks, paused voices and outgoing music fades are stopped once, and stopped handles cannot resume outside the voice registry. Pending effects and tracks requested before Stop All cannot start on load completion; cached buffers and the device remain reusable, and disposal uses the same shutdown path.+- **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.diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.tsindex dad8f1471..597b4d23a 100644--- a/sdk/src/audio/Audio.ts+++ b/sdk/src/audio/Audio.ts@@ -107,6 +107,7 @@ export class AudioAPI {private bufferBudgetOverride_: number | null = null;private bgmHandle_: AudioHandle | null = null;private bgmRequest_ = 0;+ private playbackEpoch_ = 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@@ -370,12 +371,13 @@ export class AudioAPI {*/async playTrack(url: string, config: PlayConfig = {}): Promise<AudioHandle | null> {if (this.disposed_) return null;+ const epoch = this.playbackEpoch_;try {await this.ensureBuffer_(url, () => this.backend_.loadBuffer(url));} catch {return null;}- if (this.disposed_) return null;+ if (this.disposed_ || epoch !== this.playbackEpoch_) return null;const buffer = this.lookupBuffer_(url);if (!buffer) return null;if (config.bus) this.ensureBus(config.bus);@@ -388,6 +390,7 @@ export class AudioAPI {pan?: number;priority?: number;}): AudioHandle {+ const epoch = this.playbackEpoch_;const playConfig = {bus: 'sfx',volume: config?.volume,@@ -399,7 +402,7 @@ export class AudioAPI {if (!buffer) {const pending = this.createDeferredHandle_();this.preload(url).then(() => {- if (this.disposed_) return;+ if (this.disposed_ || epoch !== this.playbackEpoch_) return;const buf = this.lookupBuffer_(url);if (buf) {pending.resolve(this.playVoice_(buf, playConfig));@@ -462,10 +465,19 @@ export class AudioAPI {stopAll(): void {this.bgmRequest_++;- this.cancelFades_();- if (this.bgmHandle_) {- this.bgmHandle_.stop();- this.bgmHandle_ = null;+ this.playbackEpoch_++;+ const voices = this.softVoices_;+ this.softVoices_ = [];+ this.bgmHandle_ = null;+ this.fades_.length = 0;+ this.fadingOut_.clear();+ const stopped = new Set<AudioHandle>();+ for (const voice of voices) {+ voice.paused = false;+ if (!stopped.has(voice.handle)) {+ stopped.add(voice.handle);+ voice.handle.stop();+ }}}@@ -633,6 +645,7 @@ export class AudioAPI {get maxVoices(): number { return this.maxVoices_; }private playVoice_(buffer: AudioBufferHandle, config: PlayConfig): AudioHandle {+ if (this.disposed_) return silentHandle();const bus = config.bus ?? 'sfx';const base = config.volume ?? 1;const priority = config.priority ?? 0;@@ -782,16 +795,10 @@ export class AudioAPI {dispose(): void {this.disposed_ = true;- this.cancelFades_();- if (this.bgmHandle_) {- this.bgmHandle_.stop();- this.bgmHandle_ = null;- }// Scripted effects and AudioSource voices also belong to this device.// Closing a Web Audio context alone leaves their handles marked playing,// and a different backend may require explicit stops before disposal.- for (const voice of this.softVoices_) voice.handle.stop();- this.softVoices_ = [];+ this.stopAll();for (const entry of this.bufferCache_.values()) {this.backend_?.unloadBuffer(entry.handle);}diff --git a/sdk/tests/audio-play-intent.test.ts b/sdk/tests/audio-play-intent.test.tsindex 036be20fe..4dd934548 100644--- a/sdk/tests/audio-play-intent.test.ts+++ b/sdk/tests/audio-play-intent.test.ts@@ -74,3 +74,43 @@ it.each([false, true])('an immediate stop ends outgoing BGM while repeated fadeexpect(handle.isPlaying).toBe(false);expect(handle.stop).toHaveBeenCalledOnce();});++it('stopAll stops every owned voice, retires paused handles and keeps the device reusable', async () => {+ const { audio, backend } = create();+ await audio.preloadFromData('ready.wav', new ArrayBuffer(8));+ const effect = audio.playSFX('ready.wav');+ effect.pause();+ audio.playBuffer({ id: 2, duration: 1 }, { bus: 'voice' });+ audio.playBGM('ready.wav');+ audio.playBGM('ready.wav', { crossFade: 1 });+ const handles = backend.play.mock.results.map(result => result.value);+ audio.stopAll();+ expect(handles.every(handle => !handle.isPlaying)).toBe(true);+ for (const handle of handles) expect(handle.stop).toHaveBeenCalledOnce();+ effect.resume();+ expect(handles[0].resume).not.toHaveBeenCalled();+ expect(backend.dispose).not.toHaveBeenCalled();+ expect(audio.getBufferHandle('ready.wav')).toBeDefined();+ expect(audio.playSFX('ready.wav').isPlaying).toBe(true);+});++it('stopAll cancels pending effect and track starts while retaining their loaded buffers', async () => {+ const { audio, backend } = create();+ const effect = audio.playSFX('effect.wav');+ const track = audio.playTrack('track.wav');+ audio.stopAll();+ await finish(audio, 'effect.wav', 1);+ await finish(audio, 'track.wav', 2);+ expect(await track).toBeNull();+ effect.resume();+ expect(backend.play).not.toHaveBeenCalled();+ expect(audio.getBufferStats().bufferCount).toBe(2);+ expect(audio.playSFX('effect.wav').isPlaying).toBe(true);+});++it('does not send a new buffer voice to a disposed device', () => {+ const { audio, backend } = create();+ audio.dispose();+ expect(audio.playBuffer({ id: 1, duration: 1 }).isPlaying).toBe(false);+ expect(backend.play).not.toHaveBeenCalled();+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 0716c6364..d206b6858 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): stop all owned voices and pending starts':+ { note: 'Stop All stops every owned audio voice and pending start.' },'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':