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: resolve audio module review issues

esengine1cfb24baa9a3
diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.ts
index 0aa9e01a9..ff81e8f80 100644
--- a/sdk/src/audio/Audio.ts
+++ b/sdk/src/audio/Audio.ts
@@ -8,6 +8,7 @@ export class Audio {
private static bgmHandle_: AudioHandle | null = null;
private static bgmVolume_ = 1.0;
private static fadeAnimId_ = 0;
+ private static disposed_ = false;
static init(backend: PlatformAudioBackend, mixer: AudioMixer | null = null): void {
this.backend_ = backend;
@@ -15,6 +16,7 @@ export class Audio {
this.bufferCache_.clear();
this.bgmHandle_ = null;
this.bgmVolume_ = 1.0;
+ this.disposed_ = false;
if (this.fadeAnimId_) {
cancelAnimationFrame(this.fadeAnimId_);
this.fadeAnimId_ = 0;
@@ -37,31 +39,28 @@ export class Audio {
pan?: number;
priority?: number;
}): AudioHandle {
+ const playConfig = {
+ bus: 'sfx',
+ volume: config?.volume,
+ playbackRate: config?.pitch,
+ pan: config?.pan,
+ priority: config?.priority ?? 0,
+ };
const buffer = this.bufferCache_.get(url);
if (!buffer) {
+ const pending = this.createDeferredHandle();
this.preload(url).then(() => {
+ if (this.disposed_) return;
const buf = this.bufferCache_.get(url);
if (buf) {
- this.backend_.play(buf, {
- bus: 'sfx',
- volume: config?.volume,
- playbackRate: config?.pitch,
- pan: config?.pan,
- priority: config?.priority ?? 0,
- });
+ pending.resolve(this.backend_.play(buf, playConfig));
}
}).catch(err => {
console.warn(`Failed to preload audio: ${url}`, err);
});
- return this.createPendingHandle();
+ return pending;
}
- return this.backend_.play(buffer, {
- bus: 'sfx',
- volume: config?.volume,
- playbackRate: config?.pitch,
- pan: config?.pan,
- priority: config?.priority ?? 0,
- });
+ return this.backend_.play(buffer, playConfig);
}
static playBGM(url: string, config?: {
@@ -75,14 +74,15 @@ export class Audio {
this.fadeAnimId_ = 0;
}
+ const targetVolume = config?.volume ?? 1.0;
+ const oldVolume = this.bgmVolume_;
+ this.bgmVolume_ = targetVolume;
+
if (this.bgmHandle_ && config?.crossFade) {
- this.fadeOut(this.bgmHandle_, config.crossFade, this.bgmVolume_);
+ this.fadeOut(this.bgmHandle_, config.crossFade, oldVolume);
} else if (this.bgmHandle_) {
this.bgmHandle_.stop();
}
-
- const targetVolume = config?.volume ?? 1.0;
- this.bgmVolume_ = targetVolume;
const fadeInDuration = config?.fadeIn ?? config?.crossFade;
this.bgmHandle_ = this.backend_.play(buffer, {
@@ -101,6 +101,7 @@ export class Audio {
play(buffer);
} else {
this.preload(url).then(() => {
+ if (this.disposed_) return;
const buf = this.bufferCache_.get(url);
if (buf) {
play(buf);
@@ -163,6 +164,7 @@ export class Audio {
}
static dispose(): void {
+ this.disposed_ = true;
if (this.fadeAnimId_) {
cancelAnimationFrame(this.fadeAnimId_);
this.fadeAnimId_ = 0;
@@ -211,19 +213,22 @@ export class Audio {
this.fadeAnimId_ = requestAnimationFrame(tick);
}
- private static createPendingHandle(): AudioHandle {
- return {
+ private static createDeferredHandle(): AudioHandle & { resolve(real: AudioHandle): void } {
+ let real: AudioHandle | null = null;
+ const handle: AudioHandle & { resolve(r: AudioHandle): void } = {
id: -1,
- stop() {},
- pause() {},
- resume() {},
- setVolume() {},
- setPan() {},
- setLoop() {},
- setPlaybackRate() {},
- isPlaying: false,
- currentTime: 0,
- duration: 0,
+ stop() { real?.stop(); },
+ pause() { real?.pause(); },
+ resume() { real?.resume(); },
+ setVolume(v: number) { real?.setVolume(v); },
+ setPan(p: number) { real?.setPan(p); },
+ setLoop(l: boolean) { real?.setLoop(l); },
+ setPlaybackRate(r: number) { real?.setPlaybackRate(r); },
+ get isPlaying() { return real?.isPlaying ?? false; },
+ get currentTime() { return real?.currentTime ?? 0; },
+ get duration() { return real?.duration ?? 0; },
+ resolve(r: AudioHandle) { real = r; },
};
+ return handle;
}
}
diff --git a/sdk/src/audio/AudioPlugin.ts b/sdk/src/audio/AudioPlugin.ts
index e491d8f40..df1a60ae9 100644
--- a/sdk/src/audio/AudioPlugin.ts
+++ b/sdk/src/audio/AudioPlugin.ts
@@ -19,6 +19,7 @@ export interface AudioPluginConfig {
export class AudioPlugin implements Plugin {
name = 'AudioPlugin';
private config_: AudioPluginConfig;
+ private activeSourceHandles_: Map<number, AudioHandle> | null = null;
constructor(config: AudioPluginConfig = {}) {
this.config_ = config;
@@ -40,6 +41,8 @@ export class AudioPlugin implements Plugin {
}
const activeSourceHandles = new Map<number, AudioHandle>();
+ this.activeSourceHandles_ = activeSourceHandles;
+ let spatialListenerWarned = false;
app.addSystemToSchedule(
Schedule.PreUpdate,
@@ -50,6 +53,7 @@ export class AudioPlugin implements Plugin {
let listenerX = 0;
let listenerY = 0;
+ let hasListener = false;
const listeners = world.getEntitiesWithComponents([AudioListener, WorldTransform]);
for (const entity of listeners) {
const listener = world.get(entity, AudioListener) as AudioListenerData;
@@ -57,11 +61,12 @@ export class AudioPlugin implements Plugin {
const wt = world.get(entity, WorldTransform) as WorldTransformData;
listenerX = wt.position.x;
listenerY = wt.position.y;
+ hasListener = true;
break;
}
}
- const sources = world.getEntitiesWithComponents([AudioSource, WorldTransform]);
+ const sources = world.getEntitiesWithComponents([AudioSource]);
const liveEntities = new Set<number>();
for (const entity of sources) {
@@ -69,8 +74,6 @@ export class AudioPlugin implements Plugin {
if (!source.enabled || !source.clip) continue;
liveEntities.add(entity as number);
- const wt = world.get(entity, WorldTransform) as WorldTransformData;
-
if (source.playOnAwake && !activeSourceHandles.has(entity)) {
const buffer = Audio.getBufferHandle(source.clip);
if (buffer) {
@@ -79,7 +82,6 @@ export class AudioPlugin implements Plugin {
volume: source.volume,
loop: source.loop,
playbackRate: source.pitch,
- priority: source.priority,
});
activeSourceHandles.set(entity, handle);
} else {
@@ -95,8 +97,17 @@ export class AudioPlugin implements Plugin {
activeSourceHandles.delete(entity);
continue;
}
- const dx = wt.position.x - listenerX;
- const dy = wt.position.y - listenerY;
+
+ if (!hasListener && !spatialListenerWarned) {
+ console.warn('[AudioPlugin] spatial audio used but no AudioListener entity found');
+ spatialListenerWarned = true;
+ }
+
+ const wt = world.tryGet?.(entity, WorldTransform) as WorldTransformData | undefined;
+ const srcX = wt?.position.x ?? 0;
+ const srcY = wt?.position.y ?? 0;
+ const dx = srcX - listenerX;
+ const dy = srcY - listenerY;
const distance = Math.sqrt(dx * dx + dy * dy);
const spatialConfig: SpatialAudioConfig = {
@@ -108,7 +119,7 @@ export class AudioPlugin implements Plugin {
const attenuation = calculateAttenuation(distance, spatialConfig);
const pan = calculatePanning(
- wt.position.x, wt.position.y,
+ srcX, srcY,
listenerX, listenerY,
source.maxDistance
);
@@ -130,6 +141,12 @@ export class AudioPlugin implements Plugin {
}
cleanup(): void {
+ if (this.activeSourceHandles_) {
+ for (const handle of this.activeSourceHandles_.values()) {
+ handle.stop();
+ }
+ this.activeSourceHandles_.clear();
+ }
Audio.dispose();
}
}
diff --git a/sdk/src/audio/AudioPool.ts b/sdk/src/audio/AudioPool.ts
index bea587126..9a7a08660 100644
--- a/sdk/src/audio/AudioPool.ts
+++ b/sdk/src/audio/AudioPool.ts
@@ -3,7 +3,6 @@ export interface PooledAudioNode {
panner: StereoPannerNode;
source: AudioBufferSourceNode | null;
inUse: boolean;
- priority: number;
startTime: number;
}
@@ -30,12 +29,11 @@ export class AudioPool {
panner,
source: null,
inUse: false,
- priority: 0,
startTime: 0,
};
}
- acquire(priority: number = 0): PooledAudioNode {
+ acquire(): PooledAudioNode {
let freeNode = this.pool_.find(n => !n.inUse);
if (!freeNode) {
@@ -44,7 +42,6 @@ export class AudioPool {
}
freeNode.inUse = true;
- freeNode.priority = priority;
freeNode.startTime = this.context_.currentTime;
freeNode.gain.gain.value = 1.0;
freeNode.panner.pan.value = 0;
@@ -60,7 +57,6 @@ export class AudioPool {
node.source = null;
}
node.inUse = false;
- node.priority = 0;
this.activeCount_--;
}
diff --git a/sdk/src/audio/SpatialAudio.ts b/sdk/src/audio/SpatialAudio.ts
index c25109863..50151de6d 100644
--- a/sdk/src/audio/SpatialAudio.ts
+++ b/sdk/src/audio/SpatialAudio.ts
@@ -25,22 +25,27 @@ export function calculateAttenuation(
const { model, refDistance, maxDistance, rolloff } = config;
const d = Math.max(distance, 0.001);
+ let result: number;
switch (model) {
case AttenuationModel.Linear: {
const range = maxDistance - refDistance;
if (range <= 0) return 1.0;
const clamped = Math.min(Math.max(d, refDistance), maxDistance);
- return 1 - (clamped - refDistance) / range;
+ result = 1 - (clamped - refDistance) / range;
+ break;
}
case AttenuationModel.Inverse: {
- return refDistance / Math.max(d, refDistance);
+ result = refDistance / Math.max(d, refDistance);
+ break;
}
case AttenuationModel.Exponential: {
- return Math.pow(Math.max(d, refDistance) / refDistance, -rolloff);
+ result = Math.pow(Math.max(d, refDistance) / refDistance, -rolloff);
+ break;
}
default:
return 1;
}
+ return Math.max(0, Math.min(1, result));
}
export function calculatePanning(
diff --git a/sdk/src/audio/WeChatAudioBackend.ts b/sdk/src/audio/WeChatAudioBackend.ts
index cdeecea1f..67e6df61b 100644
--- a/sdk/src/audio/WeChatAudioBackend.ts
+++ b/sdk/src/audio/WeChatAudioBackend.ts
@@ -53,8 +53,13 @@ class WeChatAudioHandle implements AudioHandle {
this.ctx_.volume = volume;
}
+ private panWarned_ = false;
+
setPan(_pan: number): void {
- // InnerAudioContext does not support panning
+ if (!this.panWarned_) {
+ console.warn('[Audio] WeChat InnerAudioContext does not support stereo panning');
+ this.panWarned_ = true;
+ }
}
setLoop(loop: boolean): void {
@@ -119,7 +124,6 @@ export class WeChatAudioBackend implements PlatformAudioBackend {
ctx.volume = config.volume ?? 1.0;
ctx.playbackRate = config.playbackRate ?? 1.0;
ctx.startTime = config.startOffset ?? 0;
- ctx.autoplay = true;
ctx.obeyMuteSwitch = false;
const handleId = ++this.nextId_;
@@ -134,6 +138,8 @@ export class WeChatAudioBackend implements PlatformAudioBackend {
}
});
+ ctx.autoplay = true;
+
return handle;
}
diff --git a/sdk/src/audio/WebAudioBackend.ts b/sdk/src/audio/WebAudioBackend.ts
index 3817f9fb5..f0680dec0 100644
--- a/sdk/src/audio/WebAudioBackend.ts
+++ b/sdk/src/audio/WebAudioBackend.ts
@@ -273,6 +273,8 @@ export class WebAudioBackend implements PlatformAudioBackend {
this.pool_ = null;
this.mixer_ = null;
this.buffers_.clear();
+ this.urlToId_.clear();
+ this.loadingUrls_.clear();
this.context_?.close();
this.context_ = null;
}
diff --git a/sdk/tests/audio-api.test.ts b/sdk/tests/audio-api.test.ts
index 8cc603bcd..c25d14a71 100644
--- a/sdk/tests/audio-api.test.ts
+++ b/sdk/tests/audio-api.test.ts
@@ -107,11 +107,21 @@ describe('Audio', () => {
);
});
- it('should return pending handle for uncached buffer', () => {
+ it('should return deferred handle for uncached buffer', () => {
const handle = Audio.playSFX('uncached.mp3');
expect(handle.id).toBe(-1);
expect(handle.isPlaying).toBe(false);
});
+
+ it('should delegate deferred handle methods after resolve', async () => {
+ await Audio.preload('deferred.mp3');
+ const mockHandle = createMockHandle({ id: 42 });
+ (backend.play as ReturnType<typeof vi.fn>).mockReturnValue(mockHandle);
+
+ const handle = Audio.playSFX('deferred.mp3');
+ handle.stop();
+ expect(mockHandle.stop).toHaveBeenCalled();
+ });
});
describe('playBGM', () => {
@@ -201,5 +211,23 @@ describe('Audio', () => {
Audio.dispose();
expect(Audio.getBufferHandle('sfx.mp3')).toBeUndefined();
});
+
+ it('should prevent in-flight preloads from playing after dispose', async () => {
+ let resolveLoad!: (v: any) => void;
+ (backend.loadBuffer as ReturnType<typeof vi.fn>).mockReturnValue(
+ new Promise(r => { resolveLoad = r; })
+ );
+
+ Audio.playSFX('slow.mp3');
+ Audio.dispose();
+
+ resolveLoad({ id: 99, duration: 1.0 });
+ await new Promise(r => setTimeout(r, 0));
+
+ expect(backend.play).not.toHaveBeenCalledWith(
+ expect.objectContaining({ id: 99 }),
+ expect.anything()
+ );
+ });
});
});
diff --git a/sdk/tests/audio-pool.test.ts b/sdk/tests/audio-pool.test.ts
index 5ae80e95e..3b122ce55 100644
--- a/sdk/tests/audio-pool.test.ts
+++ b/sdk/tests/audio-pool.test.ts
@@ -58,10 +58,9 @@ describe('AudioPool', () => {
expect(node.panner.pan.value).toBe(0);
});
- it('should set priority and startTime', () => {
+ it('should set startTime on acquire', () => {
const pool = new AudioPool(context, 4);
- const node = pool.acquire(5);
- expect(node.priority).toBe(5);
+ const node = pool.acquire();
expect(node.startTime).toBe(0);
});
diff --git a/sdk/tests/spatial-audio.test.ts b/sdk/tests/spatial-audio.test.ts
index a3a5f8c82..903b460d9 100644
--- a/sdk/tests/spatial-audio.test.ts
+++ b/sdk/tests/spatial-audio.test.ts
@@ -95,6 +95,18 @@ describe('SpatialAudio', () => {
it('should use default config when not provided', () => {
expect(calculateAttenuation(100)).toBeCloseTo(1.0);
});
+
+ it('should clamp exponential result to [0, 1] with negative rolloff', () => {
+ const config: SpatialAudioConfig = {
+ model: AttenuationModel.Exponential,
+ refDistance: 100,
+ maxDistance: 1000,
+ rolloff: -1.0,
+ };
+ const result = calculateAttenuation(200, config);
+ expect(result).toBeLessThanOrEqual(1.0);
+ expect(result).toBeGreaterThanOrEqual(0.0);
+ });
});
describe('calculatePanning', () => {
diff --git a/sdk/tests/web-audio-backend.test.ts b/sdk/tests/web-audio-backend.test.ts
index c043c64e9..2e69203a0 100644
--- a/sdk/tests/web-audio-backend.test.ts
+++ b/sdk/tests/web-audio-backend.test.ts
@@ -60,6 +60,7 @@ async function initAndLoadBuffer(backend: WebAudioBackend): Promise<{ bufferHand
const mockAudioBuffer = { duration: 1.0 };
mockCtx.decodeAudioData.mockResolvedValue(mockAudioBuffer);
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
}));
const bufferHandle = await backend.loadBuffer('sfx.mp3');
@@ -148,6 +149,7 @@ describe('WebAudioBackend', () => {
const mockArrayBuffer = new ArrayBuffer(8);
const mockAudioBuffer = { duration: 2.5, length: 44100 };
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
arrayBuffer: vi.fn().mockResolvedValue(mockArrayBuffer),
}));
mockCtx.decodeAudioData.mockResolvedValue(mockAudioBuffer);
@@ -158,6 +160,47 @@ describe('WebAudioBackend', () => {
expect(fetch).toHaveBeenCalledWith('test.mp3');
});
+ it('should throw on fetch failure', async () => {
+ await backend.initialize();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: false,
+ status: 404,
+ }));
+ await expect(backend.loadBuffer('missing.mp3')).rejects.toThrow('Failed to load audio: missing.mp3 (404)');
+ });
+
+ it('should deduplicate concurrent loads for the same URL', async () => {
+ await backend.initialize();
+ const mockCtx = (globalThis as any).__mockAudioContext;
+ mockCtx.decodeAudioData.mockResolvedValue({ duration: 1.0 });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
+ }));
+
+ const [h1, h2] = await Promise.all([
+ backend.loadBuffer('dup.mp3'),
+ backend.loadBuffer('dup.mp3'),
+ ]);
+ expect(h1.id).toBe(h2.id);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('should return cached handle for already loaded URL', async () => {
+ await backend.initialize();
+ const mockCtx = (globalThis as any).__mockAudioContext;
+ mockCtx.decodeAudioData.mockResolvedValue({ duration: 2.0 });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
+ }));
+
+ const h1 = await backend.loadBuffer('cached.mp3');
+ const h2 = await backend.loadBuffer('cached.mp3');
+ expect(h1.id).toBe(h2.id);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
it('should throw if not initialized', async () => {
await expect(backend.loadBuffer('test.mp3')).rejects.toThrow('AudioContext not initialized');
});
@@ -299,6 +342,7 @@ describe('WebAudioBackend', () => {
const mockCtx = (globalThis as any).__mockAudioContext;
mockCtx.decodeAudioData.mockResolvedValue({ duration: 1.0 });
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
}));