Skip to content

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.

fix(audio): retire platform handles before completion callbacks

yhh92d4dcd8cbad
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f069c102c..ef38808f4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **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.
- **Mini-game device resume preserves manual audio pauses.** The backend resumes only live contexts that were playing when device suspension began. Repeated suspension retains the original resume set, and stopped, ended, or disposed contexts are never restarted.
diff --git a/sdk/src/audio/MiniGameAudioBackend.ts b/sdk/src/audio/MiniGameAudioBackend.ts
index 2066f3244..400778dbc 100644
--- a/sdk/src/audio/MiniGameAudioBackend.ts
+++ b/sdk/src/audio/MiniGameAudioBackend.ts
@@ -31,14 +31,21 @@ class MiniGameAudioHandle implements AudioHandle {
this.contexts_ = contexts;
}
+ private isLive_(): boolean {
+ return !this.done_ && this.contexts_.get(this.id) === this.ctx_;
+ }
+
// Guarded so stop() after a natural end (or a double stop()) can't destroy the
// audio context twice — the second destroy() throws on-device.
private dispose_(alsoStop: boolean): void {
- if (this.done_) return;
+ if (!this.isLive_()) return;
this.done_ = true;
- if (alsoStop) this.ctx_.stop();
- this.ctx_.destroy();
this.contexts_.delete(this.id);
+ try {
+ if (alsoStop) this.ctx_.stop();
+ } finally {
+ this.ctx_.destroy();
+ }
}
stop(): void {
@@ -47,18 +54,23 @@ class MiniGameAudioHandle implements AudioHandle {
/** @internal The context ended on its own — dispose without a redundant stop(). */
onNaturalEnd(): void {
+ if (!this.isLive_() || this.ctx_.loop) return;
this.dispose_(false);
+ this.onEnd?.();
}
pause(): void {
+ if (!this.isLive_()) return;
this.ctx_.pause();
}
resume(): void {
+ if (!this.isLive_()) return;
this.ctx_.play();
}
setVolume(volume: number): void {
+ if (!this.isLive_()) return;
// The host's volume is only valid in [0,1] — out-of-range writes are
// rejected on-device rather than clamped.
this.ctx_.volume = scalar.clamp01(volume);
@@ -67,6 +79,7 @@ class MiniGameAudioHandle implements AudioHandle {
private panWarned_ = false;
setPan(_pan: number): void {
+ if (!this.isLive_()) return;
if (!this.panWarned_) {
log.warn('audio', 'mini-game audio contexts do not support stereo panning');
this.panWarned_ = true;
@@ -74,19 +87,21 @@ class MiniGameAudioHandle implements AudioHandle {
}
setLoop(loop: boolean): void {
+ if (!this.isLive_()) return;
this.ctx_.loop = loop;
}
setPlaybackRate(rate: number): void {
+ if (!this.isLive_()) return;
this.ctx_.playbackRate = rate;
}
get isPlaying(): boolean {
- return !this.ctx_.paused;
+ return this.isLive_() && !this.ctx_.paused;
}
get currentTime(): number {
- return this.ctx_.currentTime;
+ return this.isLive_() ? this.ctx_.currentTime : 0;
}
get duration(): number {
@@ -159,10 +174,7 @@ export class MiniGameAudioBackend implements PlatformAudioBackend {
this.contexts_.set(handleId, ctx);
const handle = new MiniGameAudioHandle(handleId, ctx, this.contexts_);
- ctx.onEnded(() => {
- handle.onEnd?.();
- if (!ctx.loop) handle.onNaturalEnd(); // guarded dispose (a later stop() is a no-op)
- });
+ ctx.onEnded(() => handle.onNaturalEnd());
ctx.onError((res) => {
log.error('audio', `Playback error for "${url}"`, res.errMsg);
});
diff --git a/sdk/src/audio/NativeAudioBackend.ts b/sdk/src/audio/NativeAudioBackend.ts
index bfc9a796a..e7f00150f 100644
--- a/sdk/src/audio/NativeAudioBackend.ts
+++ b/sdk/src/audio/NativeAudioBackend.ts
@@ -34,8 +34,7 @@ class NativeAudioHandle implements AudioHandle {
stop(): void {
if (this.done_) return;
this.done_ = true;
- this.audio_.stop(this.id);
- this.onDispose_();
+ try { this.audio_.stop(this.id); } finally { this.onDispose_(); }
}
/** @internal The host reported this voice ended on its own (pushed through
@@ -43,19 +42,19 @@ class NativeAudioHandle implements AudioHandle {
handleEnded_(): void {
if (this.done_) return;
this.done_ = true;
- this.onEnd?.();
this.onDispose_();
+ this.onEnd?.();
}
- pause(): void { this.audio_.pause(this.id); }
- resume(): void { this.audio_.resume(this.id); }
- setVolume(volume: number): void { this.audio_.setVolume(this.id, volume); }
- setPan(pan: number): void { this.audio_.setPan(this.id, scalar.clamp(pan, -1, 1)); }
- setLoop(loop: boolean): void { this.audio_.setLoop(this.id, loop); }
- setPlaybackRate(rate: number): void { this.audio_.setRate(this.id, rate); }
+ pause(): void { if (!this.done_) this.audio_.pause(this.id); }
+ resume(): void { if (!this.done_) this.audio_.resume(this.id); }
+ setVolume(volume: number): void { if (!this.done_) this.audio_.setVolume(this.id, volume); }
+ setPan(pan: number): void { if (!this.done_) this.audio_.setPan(this.id, scalar.clamp(pan, -1, 1)); }
+ setLoop(loop: boolean): void { if (!this.done_) this.audio_.setLoop(this.id, loop); }
+ setPlaybackRate(rate: number): void { if (!this.done_) this.audio_.setRate(this.id, rate); }
- get isPlaying(): boolean { return this.audio_.voiceState(this.id)?.playing ?? false; }
- get currentTime(): number { return this.audio_.voiceState(this.id)?.currentTime ?? 0; }
+ get isPlaying(): boolean { return !this.done_ && (this.audio_.voiceState(this.id)?.playing ?? false); }
+ get currentTime(): number { return this.done_ ? 0 : this.audio_.voiceState(this.id)?.currentTime ?? 0; }
get duration(): number { return this.duration_; }
}
diff --git a/sdk/tests/minigame-audio-backend.test.ts b/sdk/tests/minigame-audio-backend.test.ts
index ad6d46caf..5c780e420 100644
--- a/sdk/tests/minigame-audio-backend.test.ts
+++ b/sdk/tests/minigame-audio-backend.test.ts
@@ -70,6 +70,44 @@ describe('MiniGameAudioBackend', () => {
});
describe('stop', () => {
+ it.each(['stop', 'end', 'dispose'])('a handle retired by %s ignores writes and reports no playback', async kind => {
+ const buffer = await backend.loadBuffer('a.mp3'), handle = backend.play(buffer, {});
+ const ctx = (globalThis as any).wx.createInnerAudioContext.mock.results.at(-1).value;
+ if (kind === 'stop') handle.stop();
+ else if (kind === 'end') ctx.onEnded.mock.calls[0][0]();
+ else backend.dispose();
+ ctx.paused = false; ctx.currentTime = 7;
+ const volume = ctx.volume, loop = ctx.loop, rate = ctx.playbackRate;
+ ctx.play.mockClear(); ctx.pause.mockClear();
+ handle.pause(); handle.resume(); handle.setVolume(.2); handle.setLoop(true); handle.setPlaybackRate(2); handle.stop();
+ expect(ctx.play).not.toHaveBeenCalled(); expect(ctx.pause).not.toHaveBeenCalled();
+ expect([ctx.volume, ctx.loop, ctx.playbackRate]).toEqual([volume, loop, rate]);
+ expect(handle.isPlaying).toBe(false); expect(handle.currentTime).toBe(0);
+ expect(ctx.destroy).toHaveBeenCalledOnce();
+ });
+ it('natural completion is terminal before callbacks run and is delivered only once', async () => {
+ const buffer = await backend.loadBuffer('a.mp3'), handle = backend.play(buffer, {});
+ const ctx = (globalThis as any).wx.createInnerAudioContext.mock.results.at(-1).value;
+ handle.onEnd = vi.fn(() => { expect(handle.isPlaying).toBe(false); expect(ctx.destroy).toHaveBeenCalledOnce(); });
+ const ended = ctx.onEnded.mock.calls[0][0]; ended(); ended();
+ expect(handle.onEnd).toHaveBeenCalledOnce(); expect(ctx.destroy).toHaveBeenCalledOnce();
+ });
+ it('a throwing completion callback cannot leave a live context behind', async () => {
+ const buffer = await backend.loadBuffer('a.mp3'), handle = backend.play(buffer, {});
+ const ctx = (globalThis as any).wx.createInnerAudioContext.mock.results.at(-1).value;
+ handle.onEnd = () => { throw Error('callback failed'); };
+ const ended = ctx.onEnded.mock.calls[0][0];
+ expect(() => ended()).toThrow('callback failed');
+ expect(ctx.destroy).toHaveBeenCalledOnce(); expect(handle.isPlaying).toBe(false);
+ expect(() => ended()).not.toThrow(); backend.dispose(); expect(ctx.destroy).toHaveBeenCalledOnce();
+ });
+ it('a loop notification does not retire a playing looping context', async () => {
+ const buffer = await backend.loadBuffer('a.mp3'), handle = backend.play(buffer, { loop: true });
+ const ctx = (globalThis as any).wx.createInnerAudioContext.mock.results.at(-1).value;
+ handle.onEnd = vi.fn(); ctx.onEnded.mock.calls[0][0]();
+ expect(handle.isPlaying).toBe(true); expect(handle.onEnd).not.toHaveBeenCalled();
+ expect(ctx.destroy).not.toHaveBeenCalled(); handle.stop(); expect(ctx.destroy).toHaveBeenCalledOnce();
+ });
it('is idempotent — never destroys the InnerAudioContext twice', async () => {
const handle = await backend.loadBuffer('audio/sfx.mp3');
const audioHandle = backend.play(handle, {});
diff --git a/sdk/tests/native-audio.test.ts b/sdk/tests/native-audio.test.ts
index 2ab2152c2..b07ed60bf 100644
--- a/sdk/tests/native-audio.test.ts
+++ b/sdk/tests/native-audio.test.ts
@@ -130,6 +130,28 @@ describe('NativeAudioBackend', () => {
expect(host.calls.stop.length).toBe(stopsBefore);
});
+ it('retires native ownership before invoking a throwing completion callback', () => {
+ const scope = audioScope(), bridge = createHostBridge(scope);
+ const backend = new NativeAudioBackend(bridge.audio!);
+ const handle = backend.play({ id: 1, duration: 1 }, {});
+ const owned = (backend as unknown as { voices_: Map<number, unknown> }).voices_;
+ handle.onEnd = () => { throw Error('callback failed'); };
+ expect(() => (scope.es_onNativeAudioEnded as (v: number) => void)(handle.id)).toThrow('callback failed');
+ expect(owned.size).toBe(0); expect(handle.isPlaying).toBe(false);
+ });
+
+ it.each(['stop', 'end'])('a native handle retired by %s ignores later parameter writes', kind => {
+ const scope = audioScope(), bridge = createHostBridge(scope), audio = bridge.audio!;
+ const writes = ['pause', 'resume', 'setVolume', 'setPan', 'setLoop', 'setRate'] as const;
+ const spies = writes.map(name => vi.spyOn(audio, name));
+ const backend = new NativeAudioBackend(audio), handle = backend.play({ id: 1, duration: 1 }, {});
+ if (kind === 'stop') handle.stop();
+ else (scope.es_onNativeAudioEnded as (v: number) => void)(handle.id);
+ handle.pause(); handle.resume(); handle.setVolume(.2); handle.setPan(.5); handle.setLoop(true); handle.setPlaybackRate(2);
+ for (const spy of spies) expect(spy).not.toHaveBeenCalled();
+ expect(handle.isPlaying).toBe(false); expect(handle.currentTime).toBe(0);
+ });
+
it('stop() tears the voice down through the bridge', () => {
const scope = audioScope();
const host = installAudioHost(scope);
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index f6f3be378..7a79382fc 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): 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':
{ note: 'Audio device suspension freezes volume fades.' },
'fix(audio): preserve manual minigame pauses on device resume':