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.

feat(audio): project-declared mixer state boots every runtime

esengine698719542487
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index b47f26d23..31d5b0a45 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -11,7 +11,7 @@
* import of an editor module here would break the realm bundle. Type-only
* imports are erased before resolution and are safe.
*/
-import type { SceneData, PhysicsPluginConfig } from 'esengine';
+import type { SceneData, PhysicsPluginConfig, AudioProjectConfig } from 'esengine';
/**
* Editor↔realm message-contract version. The realm reports it in `hello`; the editor
@@ -57,6 +57,8 @@ export interface PlayPayload {
physicsEnabled?: boolean;
/** Project physics world config (gravity, solver, collision matrix) — forwarded. */
physicsConfig?: PhysicsPluginConfig;
+ /** Project mixer state (bus volumes / effects / duck rules) — forwarded. */
+ audioConfig?: AudioProjectConfig;
/** Bitmask of render layers (0..31) that y-sort within the layer — forwarded. */
ySortLayers?: number;
/** Multiplayer preview role; absent = a plain single-player session. */
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index 243247fbb..db18c1940 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -106,6 +106,7 @@ export const projectMessages = defineMessages({
'proj.savePackagingFailed': { en: 'Failed to save packaging settings', zh: '保存打包设置失败' },
'proj.savePlatformFailed': { en: 'Failed to save platform settings', zh: '保存平台设置失败' },
'proj.savePhysicsFailed': { en: 'Failed to save physics setting', zh: '保存物理设置失败' },
+ 'proj.saveAudioFailed': { en: 'Failed to save audio setting', zh: '保存音频设置失败' },
'proj.startupScene': { en: 'Startup scene: {name}', zh: '启动场景:{name}' },
'proj.saveStartupSceneFailed': { en: 'Failed to save startup scene', zh: '保存启动场景失败' },
'proj.excludedFromExport': { en: 'Excluded from export: {name}', zh: '已从导出中排除:{name}' },
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index bb5838ce5..184bcb02b 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -197,6 +197,7 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
wasmBaseUrl: wasmBase.replace(/\/$/, ''),
physicsEnabled: msg.physicsEnabled,
physicsConfig: msg.physicsConfig,
+ audioConfig: msg.audioConfig,
enableStats: true, // editor profiler: per-phase / per-system frame timing
});
// Realm-local debug handle for automation/diagnostics (mirrors the headless
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index ec29e5a2f..8bc6df04f 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -3,7 +3,7 @@
import { createStore } from 'zustand/vanilla';
import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, diffAgainstSource, applyOverridesToSource, setTextureParams, TextureFilter, TextureWrap, Renderer } from 'esengine';
import { readTextureImportSettings } from './assetImporter';
-import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig } from 'esengine';
+import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig } from 'esengine';
import { EngineHost } from '@/engine/EngineHost';
import { SceneModel } from '@/engine/SceneModel';
import { Reconciler } from '@/engine/Reconciler';
@@ -786,6 +786,7 @@ class ProjectStoreImpl {
assetManifest: Record<string, string>;
physicsEnabled?: boolean;
physicsConfig?: PhysicsPluginConfig;
+ audioConfig?: AudioProjectConfig;
ySortLayers?: number;
} | null {
const sceneData = SceneModel.serialize();
@@ -815,12 +816,39 @@ class ProjectStoreImpl {
physicsConfig.collisionLayerMasks = f.collisionLayerMasks;
}
const ySortLayers = this.ySortMask();
+ const audioConfig = this.audioFeature();
return {
sceneData, assetManifest, physicsEnabled: f.enabled, physicsConfig,
+ ...(audioConfig.buses ? { audioConfig } : {}),
...(ySortLayers !== 0 ? { ySortLayers } : {}),
};
}
+ /** The project's declared mixer state (Project Settings → Audio / the Mixer). */
+ audioFeature(): AudioProjectConfig {
+ return this.state?.features?.audio ?? {};
+ }
+
+ /**
+ * Replace the project mixer state and persist to `project.esproject`. Rewrites
+ * the RAW manifest JSON so unmodeled fields survive; in-memory state first so
+ * the Mixer reflects immediately.
+ */
+ async setAudio(config: AudioProjectConfig): Promise<void> {
+ const st = this.state;
+ if (!st) return;
+ const features: ProjectFeatures = { ...st.features, audio: config };
+ this.store.setState({ project: { ...st, features } });
+ try {
+ const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;
+ raw.features = { ...(raw.features as Record<string, unknown> ?? {}), audio: config };
+ await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');
+ } catch (e) {
+ Toasts.push(t('proj.saveAudioFailed'), 'error');
+ console.error('[project] setAudio write failed', e);
+ }
+ }
+
/** The project's declared physics feature, with defaults (for Project Settings). The
* solver defaults mirror the runtime fallbacks so the UI shows the effective values. */
physicsFeature(): {
diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.ts
index a1f473fe4..47d4f5620 100644
--- a/desktop/src/project/format.ts
+++ b/desktop/src/project/format.ts
@@ -18,6 +18,8 @@
* into workspace.json.
*/
+import { parseAudioProjectConfig, type AudioProjectConfig } from 'esengine';
+
export const PROJECT_FORMAT_VERSION = '1';
export const PROJECT_MANIFEST_FILE = 'project.esproject';
export const WORKSPACE_DIR = '.esengine';
@@ -87,6 +89,8 @@ export interface ProjectFeatures {
/** Indices of sorting layers that y-sort within the layer (top-down occlusion). */
ySortLayers?: number[];
};
+ /** Project mixer state (bus volumes / custom buses / effects / duck rules). */
+ audio?: AudioProjectConfig;
}
export type ScreenOrientation = 'portrait' | 'landscape';
@@ -276,6 +280,10 @@ export function parseManifest(raw: unknown): ProjectManifest {
}
if (Object.keys(rendering).length > 0) features.rendering = rendering;
}
+ if (f.audio && typeof f.audio === 'object') {
+ const audio = parseAudioProjectConfig(f.audio);
+ if (audio.buses) features.audio = audio;
+ }
if (Object.keys(features).length > 0) manifest.features = features;
}
if (o.packaging && typeof o.packaging === 'object') {
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 807d1ecf1..959788fae 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1150 stable · 17 beta · 1 deprecated
+Symbols: 1154 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -552,6 +552,7 @@ ResourceDef<AudioAPI>
baseUrl: string
bufferBudget: number
dispose: () => void
+ensureBus: (name: string, parent?: string) => boolean
getBufferHandle: (url: string) => AudioBufferHandle | undefined
getBufferStats: () => AudioBufferStats
getBusDucking: (target: string) => BusDuckRule | null
@@ -621,6 +622,16 @@ parent: string | undefined
volume: number | undefined
```
+## AudioBusDecl — interface
+```
+duck: BusDuckRule | undefined
+effects: BusEffectDef[] | undefined
+muted: boolean | undefined
+name: string
+parent: string | undefined
+volume: number | undefined
+```
+
## AudioHandle — interface
```
currentTime: number
@@ -701,6 +712,11 @@ static new (context: AudioContext, initialSize?: number): AudioPool
static prototype: AudioPool
```
+## AudioProjectConfig — interface
+```
+buses: AudioBusDecl[] | undefined
+```
+
## AudioSource — const
```
ComponentDef<AudioSourceData>
@@ -4271,6 +4287,7 @@ app: App
assetBaseUrl: string | undefined
assetManifest: Record<string, string>
assetPathMap: Record<string, string> | undefined
+audioConfig: AudioProjectConfig | undefined
canvas: HTMLCanvasElement
catalogData: CatalogData | null | undefined
enableStats: boolean | undefined
@@ -4289,6 +4306,7 @@ wasmBaseUrl: string | undefined
app: App
assetPathMap: Record<string, string> | undefined
assets: Record<string, string>
+audioConfig: AudioProjectConfig | undefined
canvas: HTMLCanvasElement
firstScene: string
manifest: AddressableManifest | null | undefined
@@ -4998,6 +5016,7 @@ textureCacheBudget: number | undefined
```
app: App
aspectRatio: number | undefined
+audioConfig: AudioProjectConfig | undefined
catalog: Catalog | undefined
firstScene: string
manifest: AddressableManifest | ManifestModel | null | undefined
@@ -7171,6 +7190,11 @@ AiRegistry<AiContext>
AnimationPlugin
```
+## applyAudioProjectConfig — function
+```
+(audio: AudioAPI, config: AudioProjectConfig | undefined): void
+```
+
## applyBuildRuntimeConfig — function
```
(app: { setMaxDeltaTime(v: number): void; setMaxFixedSteps(v: number): void; }, config: RuntimeBuildConfig): void
@@ -8261,6 +8285,11 @@ NavPlugin
(raw: any): TimelineAsset
```
+## parseAudioProjectConfig — function
+```
+(raw: unknown): AudioProjectConfig
+```
+
## parseBusEffects — function
```
(raw: unknown): BusEffectDef[]
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index c63689d02..d05d246bd 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1149 stable · 19 beta · 1 deprecated
+Symbols: 1153 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -547,6 +547,7 @@ ResourceDef<AudioAPI>
baseUrl: string
bufferBudget: number
dispose: () => void
+ensureBus: (name: string, parent?: string) => boolean
getBufferHandle: (url: string) => AudioBufferHandle | undefined
getBufferStats: () => AudioBufferStats
getBusDucking: (target: string) => BusDuckRule | null
@@ -616,6 +617,16 @@ parent: string | undefined
volume: number | undefined
```
+## AudioBusDecl — interface
+```
+duck: BusDuckRule | undefined
+effects: BusEffectDef[] | undefined
+muted: boolean | undefined
+name: string
+parent: string | undefined
+volume: number | undefined
+```
+
## AudioHandle — interface
```
currentTime: number
@@ -696,6 +707,11 @@ static new (context: AudioContext, initialSize?: number): AudioPool
static prototype: AudioPool
```
+## AudioProjectConfig — interface
+```
+buses: AudioBusDecl[] | undefined
+```
+
## AudioSource — const
```
ComponentDef<AudioSourceData>
@@ -4266,6 +4282,7 @@ app: App
assetBaseUrl: string | undefined
assetManifest: Record<string, string>
assetPathMap: Record<string, string> | undefined
+audioConfig: AudioProjectConfig | undefined
canvas: HTMLCanvasElement
catalogData: CatalogData | null | undefined
enableStats: boolean | undefined
@@ -4284,6 +4301,7 @@ wasmBaseUrl: string | undefined
app: App
assetPathMap: Record<string, string> | undefined
assets: Record<string, string>
+audioConfig: AudioProjectConfig | undefined
canvas: HTMLCanvasElement
firstScene: string
manifest: AddressableManifest | null | undefined
@@ -4993,6 +5011,7 @@ textureCacheBudget: number | undefined
```
app: App
aspectRatio: number | undefined
+audioConfig: AudioProjectConfig | undefined
catalog: Catalog | undefined
firstScene: string
manifest: AddressableManifest | ManifestModel | null | undefined
@@ -7166,6 +7185,11 @@ AiRegistry<AiContext>
AnimationPlugin
```
+## applyAudioProjectConfig — function
+```
+(audio: AudioAPI, config: AudioProjectConfig | undefined): void
+```
+
## applyBuildRuntimeConfig — function
```
(app: { setMaxDeltaTime(v: number): void; setMaxFixedSteps(v: number): void; }, config: RuntimeBuildConfig): void
@@ -8266,6 +8290,11 @@ NodePlatformAdapter
(raw: any): TimelineAsset
```
+## parseAudioProjectConfig — function
+```
+(raw: unknown): AudioProjectConfig
+```
+
## parseBusEffects — function
```
(raw: unknown): BusEffectDef[]
diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.ts
index 711ffa5fb..079490c1d 100644
--- a/sdk/src/audio/Audio.ts
+++ b/sdk/src/audio/Audio.ts
@@ -376,6 +376,16 @@ export class AudioAPI {
}
}
+ /** Ensure a named bus exists (creating it under `parent` ?? master).
+ * False on backends without a mixer graph. */
+ ensureBus(name: string, parent?: string): boolean {
+ if (!this.mixer_) return false;
+ if (!this.mixer_.getBus(name)) {
+ this.mixer_.createBus({ name, ...(parent ? { parent } : {}) });
+ }
+ return true;
+ }
+
setBusVolume(busName: string, volume: number): void {
const bus = this.mixer_?.getBus(busName);
if (bus) {
diff --git a/sdk/src/audio/AudioProjectConfig.ts b/sdk/src/audio/AudioProjectConfig.ts
new file mode 100644
index 000000000..3c117af98
--- /dev/null
+++ b/sdk/src/audio/AudioProjectConfig.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file AudioProjectConfig.ts
+ * @brief Project-declared mixer state (project.esproject `features.audio`):
+ * bus volumes, custom buses, insert chains, duck rules. The runtime
+ * applies it at boot; the editor Mixer edits the same shape. On
+ * backends without a WebAudio graph every step degrades to a no-op
+ * through the AudioAPI guards.
+ */
+
+import type { AudioAPI } from './Audio';
+import type { BusDuckRule } from './AudioMixer';
+import { parseBusEffects, type BusEffectDef } from './BusEffects';
+
+export interface AudioBusDecl {
+ name: string;
+ /** Parent bus for buses beyond the default five (default parent: master). */
+ parent?: string;
+ volume?: number;
+ muted?: boolean;
+ effects?: BusEffectDef[];
+ duck?: BusDuckRule;
+}
+
+export interface AudioProjectConfig {
+ buses?: AudioBusDecl[];
+}
+
+const clamp01 = (v: number) => Math.max(0, Math.min(1, v));
+
+/** Normalize arbitrary JSON into a valid config (tolerant; drops junk). */
+export function parseAudioProjectConfig(raw: unknown): AudioProjectConfig {
+ const buses: AudioBusDecl[] = [];
+ const rawBuses = (raw as { buses?: unknown } | undefined)?.buses;
+ for (const b of Array.isArray(rawBuses) ? rawBuses : []) {
+ if (!b || typeof b !== 'object' || typeof b.name !== 'string' || !b.name) continue;
+ const decl: AudioBusDecl = { name: b.name };
+ if (typeof b.parent === 'string' && b.parent) decl.parent = b.parent;
+ if (typeof b.volume === 'number' && Number.isFinite(b.volume)) decl.volume = clamp01(b.volume);
+ if (typeof b.muted === 'boolean') decl.muted = b.muted;
+ const effects = parseBusEffects(b.effects);
+ if (effects.length > 0) decl.effects = effects;
+ const d = b.duck as BusDuckRule | undefined;
+ if (d && typeof d === 'object' && typeof d.trigger === 'string' && d.trigger
+ && typeof d.amount === 'number' && Number.isFinite(d.amount)) {
+ decl.duck = {
+ trigger: d.trigger,
+ amount: clamp01(d.amount),
+ ...(typeof d.attack === 'number' ? { attack: d.attack } : {}),
+ ...(typeof d.release === 'number' ? { release: d.release } : {}),
+ ...(typeof d.threshold === 'number' ? { threshold: d.threshold } : {}),
+ };
+ }
+ buses.push(decl);
+ }
+ return buses.length > 0 ? { buses } : {};
+}
+
+/**
+ * Apply the declared mixer state: create missing buses, then set volume /
+ * mute / effects / duck per declaration. Full-state semantics — a declared
+ * bus with no `duck` clears any prior rule, so the editor can re-apply live.
+ */
+export function applyAudioProjectConfig(audio: AudioAPI, config: AudioProjectConfig | undefined): void {
+ for (const bus of config?.buses ?? []) {
+ if (!audio.ensureBus(bus.name, bus.parent)) return; // no mixer: nothing applies
+ if (bus.volume !== undefined) audio.setBusVolume(bus.name, bus.volume);
+ if (bus.muted !== undefined) audio.muteBus(bus.name, bus.muted);
+ audio.setBusEffects(bus.name, bus.effects ?? []);
+ audio.setBusDucking(bus.name, bus.duck ?? null);
+ }
+}
diff --git a/sdk/src/audio/index.ts b/sdk/src/audio/index.ts
index e2aae95f7..9b05971fc 100644
--- a/sdk/src/audio/index.ts
+++ b/sdk/src/audio/index.ts
@@ -8,6 +8,10 @@ export {
type BusEffectDef, type FilterEffectDef, type ReverbEffectDef, type CompressorEffectDef,
type EffectNodes,
} from './BusEffects';
+export {
+ parseAudioProjectConfig, applyAudioProjectConfig,
+ type AudioProjectConfig, type AudioBusDecl,
+} from './AudioProjectConfig';
export { AudioPool, type PooledAudioNode } from './AudioPool';
export { AudioPlugin, audioPlugin, type AudioPluginConfig } from './AudioPlugin';
export { AudioSource, AudioListener, type AudioSourceData, type AudioListenerData } from './AudioComponents';
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 2553e48ee..3ba2b9b18 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -295,6 +295,10 @@ export {
AudioMixer,
AudioPool,
parseBusEffects,
+ parseAudioProjectConfig,
+ applyAudioProjectConfig,
+ type AudioProjectConfig,
+ type AudioBusDecl,
type BusEffectDef,
type FilterEffectDef,
type ReverbEffectDef,
diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.ts
index e4e7d4b14..ff93baf00 100644
--- a/sdk/src/playRealmRuntime.ts
+++ b/sdk/src/playRealmRuntime.ts
@@ -25,6 +25,7 @@ import { Catalog, type CatalogData } from './asset/Catalog';
import type { AddressableManifest } from './asset/AddressableManifest';
import type { SceneData } from './scene';
import type { PhysicsPluginConfig } from './physics/PhysicsPlugin';
+import type { AudioProjectConfig } from './audio/AudioProjectConfig';
import { fetchDecodePixels } from './asset/imageDecode';
import { extractUuid, UUID_REF_PREFIX } from './asset/AssetRegistry';
@@ -71,6 +72,8 @@ export interface PlayRealmRuntimeConfig {
/** Project-declared physics world config (gravity, solver tuning, collision-layer
* masks, sleep/continuous) from the editor's Project Settings. */
physicsConfig?: PhysicsPluginConfig;
+ /** Project-declared mixer state (bus volumes / effects / duck rules). */
+ audioConfig?: AudioProjectConfig;
/** Turn on per-phase / per-system frame timing (editor profiler; off in shipped games). */
enableStats?: boolean;
}
@@ -172,6 +175,7 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Prom
aspectRatio: canvas.width / canvas.height,
physicsEnabled: config.physicsEnabled,
physicsConfig: config.physicsConfig,
+ audioConfig: config.audioConfig,
// Physics (and spine) are acquired from app.sideModules — the fetch host
// createWebApp built from this realm's wasmBaseUrl.
});
diff --git a/sdk/src/playableRuntime.ts b/sdk/src/playableRuntime.ts
index 3348c4083..61932fc56 100644
--- a/sdk/src/playableRuntime.ts
+++ b/sdk/src/playableRuntime.ts
@@ -12,6 +12,7 @@
*/
import type { App } from './app';
import type { ESEngineModule } from './wasm';
+import type { AudioProjectConfig } from './audio/AudioProjectConfig';
import { initRuntime } from './runtimeLoader';
import type { RuntimeAssetSource } from './runtimeAssets';
import { EmbeddedBackend } from './asset/Backend';
@@ -36,6 +37,8 @@ export interface PlayableRuntimeConfig {
scenes: Array<{ name: string; data: SceneData }>;
firstScene: string;
physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };
+ /** Project-declared mixer state (bus volumes / effects / duck rules). */
+ audioConfig?: AudioProjectConfig;
/** Bitmask of render layers (0..31) that y-sort within the layer (Project Settings → Rendering). */
ySortLayers?: number;
manifest?: AddressableManifest | null;
@@ -111,6 +114,7 @@ export async function initPlayableRuntime(config: PlayableRuntimeConfig): Promis
scenes,
firstScene,
physicsConfig: config.physicsConfig,
+ audioConfig: config.audioConfig,
aspectRatio: config.canvas.width / config.canvas.height,
});
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index d7f18cefb..be366a29d 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -13,6 +13,7 @@ import type { SpineWasmModule } from './spine/SpineModuleLoader';
import { SpineManager } from './spine/SpineManager';
import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';
import { PhysicsPlugin, type PhysicsPluginConfig } from './physics/PhysicsPlugin';
+import { applyAudioProjectConfig, type AudioProjectConfig } from './audio/AudioProjectConfig';
import { SpinePlugin } from './spine/SpinePlugin';
import type { App } from './app';
import { Assets as AssetsClass } from './asset/Assets';
@@ -387,6 +388,9 @@ export interface RuntimeInitConfig {
physicsConfig?: PhysicsPluginConfig;
/** Project-declared physics enable; see {@link LoadRuntimeSceneOptions.physicsEnabled}. */
physicsEnabled?: boolean;
+ /** Project-declared mixer state (bus volumes / custom buses / effects / duck
+ * rules) — threaded from the editor's audio config, applied once at boot. */
+ audioConfig?: AudioProjectConfig;
aspectRatio?: number;
}
@@ -402,6 +406,10 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {
const assets = ensureRuntimeAssets(app, config.module, config.source, config.catalog);
if (config.manifest) assets.setManifest(config.manifest);
+ if (config.audioConfig && app.hasResource(Audio)) {
+ applyAudioProjectConfig(app.getResource(Audio), config.audioConfig);
+ }
+
const sceneOpts: Omit<LoadRuntimeSceneOptions, 'sceneData' | 'sceneName'> = {
app: config.app,
module: config.module,
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index bca5d254b..2defd8aa9 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -9,6 +9,7 @@
import { createWebApp } from './webAppFactory';
import type { ESEngineModule } from './wasm';
+import type { AudioProjectConfig } from './audio/AudioProjectConfig';
import { initRuntime } from './runtimeLoader';
import type { RuntimeAssetSource } from './runtimeAssets';
import { FileSystemBackend } from './asset/Backend';
@@ -71,6 +72,8 @@ export interface WeChatRuntimeConfig {
firstScene: string;
runtimeConfig?: RuntimeBuildConfig;
physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number };
+ /** Project-declared mixer state (routing labels only on WeChat — no DSP graph). */
+ audioConfig?: AudioProjectConfig;
/** Bitmask of render layers (0..31) that y-sort within the layer (Project Settings → Rendering). */
ySortLayers?: number;
/** id → emscripten factory (`require('./wasm/<file>.js')`); the generated
@@ -191,6 +194,7 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
scenes,
firstScene: config.firstScene,
physicsConfig: config.physicsConfig,
+ audioConfig: config.audioConfig,
aspectRatio: canvas.width / canvas.height,
});
diff --git a/sdk/tests/audio-project-config.test.ts b/sdk/tests/audio-project-config.test.ts
new file mode 100644
index 000000000..f43f360dc
--- /dev/null
+++ b/sdk/tests/audio-project-config.test.ts
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * Project audio config: tolerant parsing and full-state application through the
+ * AudioAPI surface (creates missing buses, sets volume/mute/effects/duck, clears
+ * an absent duck rule so live re-apply works).
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { parseAudioProjectConfig, applyAudioProjectConfig } from '../src/audio/AudioProjectConfig';
+import type { AudioAPI } from '../src/audio/Audio';
+
+function mockAudioApi() {
+ return {
+ ensureBus: vi.fn(() => true),
+ setBusVolume: vi.fn(),
+ muteBus: vi.fn(),
+ setBusEffects: vi.fn(() => true),
+ setBusDucking: vi.fn(() => true),
+ } as unknown as AudioAPI;
+}
+
+describe('parseAudioProjectConfig', () => {
+ it('normalizes valid buses and drops junk', () => {
+ const cfg = parseAudioProjectConfig({
+ buses: [
+ {
+ name: 'music', volume: 1.5,
+ effects: [{ type: 'filter', filter: 'lowpass', frequency: 700 }],
+ duck: { trigger: 'voice', amount: 0.3, release: 0.5 },
+ },
+ { name: '', volume: 0.5 }, // no name
+ { name: 'ambience', parent: 'sfx' }, // custom bus
+ 'nonsense',
+ ],
+ });
+ expect(cfg.buses).toEqual([
+ {
+ name: 'music', volume: 1,
+ effects: [{ type: 'filter', filter: 'lowpass', frequency: 700 }],
+ duck: { trigger: 'voice', amount: 0.3, release: 0.5 },
+ },
+ { name: 'ambience', parent: 'sfx' },
+ ]);
+ });
+
+ it('returns {} for empty or invalid input', () => {
+ expect(parseAudioProjectConfig(undefined)).toEqual({});
+ expect(parseAudioProjectConfig({ buses: [] })).toEqual({});
+ });
+});
+
+describe('applyAudioProjectConfig', () => {
+ it('ensures buses then applies volume/mute/effects/duck', () => {
+ const audio = mockAudioApi();
+ applyAudioProjectConfig(audio, {
+ buses: [{
+ name: 'ambience', parent: 'sfx', volume: 0.6, muted: true,
+ effects: [{ type: 'reverb', wet: 0.4 }],
+ duck: { trigger: 'voice', amount: 0.2 },
+ }],
+ });
+ expect(audio.ensureBus).toHaveBeenCalledWith('ambience', 'sfx');
+ expect(audio.setBusVolume).toHaveBeenCalledWith('ambience', 0.6);
+ expect(audio.muteBus).toHaveBeenCalledWith('ambience', true);
+ expect(audio.setBusEffects).toHaveBeenCalledWith('ambience', [{ type: 'reverb', wet: 0.4 }]);
+ expect(audio.setBusDucking).toHaveBeenCalledWith('ambience', { trigger: 'voice', amount: 0.2 });
+ });
+
+ it('clears effects and duck for declarations without them (full-state re-apply)', () => {
+ const audio = mockAudioApi();
+ applyAudioProjectConfig(audio, { buses: [{ name: 'music' }] });
+ expect(audio.setBusEffects).toHaveBeenCalledWith('music', []);
+ expect(audio.setBusDucking).toHaveBeenCalledWith('music', null);
+ });
+
+ it('stops silently when the backend has no mixer', () => {
+ const audio = mockAudioApi();
+ (audio.ensureBus as ReturnType<typeof vi.fn>).mockReturnValue(false);
+ applyAudioProjectConfig(audio, { buses: [{ name: 'music', volume: 0.5 }] });
+ expect(audio.setBusVolume).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op for undefined config', () => {
+ const audio = mockAudioApi();
+ applyAudioProjectConfig(audio, undefined);
+ expect(audio.ensureBus).not.toHaveBeenCalled();
+ });
+});