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(sdk): WeChat audio stop() is idempotent
esenginee75d7386d012
diff --git a/sdk/src/audio/WeChatAudioBackend.ts b/sdk/src/audio/WeChatAudioBackend.tsindex f0a3e78e9..53987d690 100644--- a/sdk/src/audio/WeChatAudioBackend.ts+++ b/sdk/src/audio/WeChatAudioBackend.ts@@ -12,6 +12,7 @@ class WeChatAudioHandle implements AudioHandle {private ctx_: WechatMinigame.InnerAudioContext;private contexts_: Map<number, WechatMinigame.InnerAudioContext>;+ private done_ = false;constructor(id: number, ctx: WechatMinigame.InnerAudioContext, contexts: Map<number, WechatMinigame.InnerAudioContext>) {this.id = id;@@ -19,12 +20,25 @@ class WeChatAudioHandle implements AudioHandle {this.contexts_ = contexts;}- stop(): void {- this.ctx_.stop();+ // Guarded so stop() after a natural end (or a double stop()) can't destroy the+ // InnerAudioContext twice — the second destroy() throws on-device.+ private dispose_(alsoStop: boolean): void {+ if (this.done_) return;+ this.done_ = true;+ if (alsoStop) this.ctx_.stop();this.ctx_.destroy();this.contexts_.delete(this.id);}+ stop(): void {+ this.dispose_(true);+ }++ /** @internal The context ended on its own — dispose without a redundant stop(). */+ onNaturalEnd(): void {+ this.dispose_(false);+ }+pause(): void {this.ctx_.pause();}@@ -125,10 +139,7 @@ export class WeChatAudioBackend implements PlatformAudioBackend {const handle = new WeChatAudioHandle(handleId, ctx, this.contexts_);ctx.onEnded(() => {handle.onEnd?.();- if (!ctx.loop) {- ctx.destroy();- this.contexts_.delete(handleId);- }+ if (!ctx.loop) handle.onNaturalEnd(); // guarded dispose (a later stop() is a no-op)});ctx.onError((res) => {log.error('audio', `Playback error for "${url}"`, res.errMsg);diff --git a/sdk/tests/wechat-audio-backend.test.ts b/sdk/tests/wechat-audio-backend.test.tsindex 9ab8aaf1f..48687073d 100644--- a/sdk/tests/wechat-audio-backend.test.ts+++ b/sdk/tests/wechat-audio-backend.test.ts@@ -62,6 +62,17 @@ describe('WeChatAudioBackend', () => {});});+ describe('stop', () => {+ it('is idempotent — never destroys the InnerAudioContext twice', async () => {+ const handle = await backend.loadBuffer('audio/sfx.mp3');+ const audioHandle = backend.play(handle, {});+ const ctx = (globalThis as any).wx.createInnerAudioContext.mock.results.at(-1).value;+ audioHandle.stop();+ audioHandle.stop(); // double stop (or a stop after the sound ended on its own)+ expect(ctx.destroy).toHaveBeenCalledTimes(1);+ });+ });+describe('play', () => {it('should create InnerAudioContext and configure it', async () => {const handle = await backend.loadBuffer('audio/sfx.mp3');