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
feat(audio): manage sound event playback lifetimes
yhh78f12b6e8886
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 43f571785..b49dc51e9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,7 +16,9 @@ published separately; it ships inside the editor.### Added-- **Sound event definitions share deterministic selection.** Beta `.esaudioevent` assets validate weighted clip slots, sequential and no-repeat selection, volume/rate ranges and event playback settings. The shared selector uses independent seeded streams for clip and parameter choices, combines duplicate audio identities, and reports empty or disabled pools. Definitions load through Assets without decoding every candidate; export dependency scanning retains all candidates and UUID references survive file moves. This provides the resource and selection layer for RM-066; automatic event playback limits, dedicated authoring, component and visual-script integration remain in progress.+- **Sound event playback owns pending and paused voices.** The per-App SoundEvents resource loads owned emitters, shares event concurrency and cooldown before clip IO, and routes selected clips through the existing Audio priority pool. Natural completion, Stop All, owner despawn, registry disconnect and App cleanup release receipts and cancel late starts. Requests expose selected parameters, lifecycle and rejection reasons; spatial events reuse source attenuation/panning. Pending admissions avoid rescanning the loading queue, and unchanged gains skip backend writes. Dedicated event authoring, components and visual-script nodes remain in progress.++- **Sound event definitions share deterministic selection.** Beta `.esaudioevent` assets validate weighted clip slots, sequential and no-repeat selection, volume/rate ranges and event playback settings. The shared selector uses independent seeded streams for clip and parameter choices, combines duplicate audio identities, and reports empty or disabled pools. Definitions load through Assets without decoding every candidate; export dependency scanning retains all candidates and UUID references survive file moves. This provides the resource and selection layer for RM-066; dedicated authoring, component and visual-script integration remain in progress.### Fixeddiff --git a/docs/astro/src/content/docs/assets/audio.mdx b/docs/astro/src/content/docs/assets/audio.mdxindex d8eec1a42..bc2fa9cf0 100644--- a/docs/astro/src/content/docs/assets/audio.mdx+++ b/docs/astro/src/content/docs/assets/audio.mdx@@ -80,10 +80,46 @@ The seed controls clip and parameter choices independently of the playback backeChanging parameter ranges preserves clip order. Playback rate changes pitch **andduration**. It does not preserve duration while shifting pitch.-The selector only chooses clips and parameters. The document also stores bus,-priority, spatial attenuation, `maxInstances` and cooldown settings; the caller-must apply these while controlling playback. Event-level playback management,-the dedicated editor, and component/visual-script integration remain in RM-066.+The selector only chooses clips and parameters. Use the managed playback resource+to apply event settings and own loading/playing lifetimes together.++### Managed event playback++```typescript+import { SoundEvents } from 'esengine';++const events = app.getResource(SoundEvents);+const emitter = await events.load('assets/steps.esaudioevent', { owner: entity, seed: 42 });+const voice = emitter?.trigger(); // Spatial events can also take a world-space position.+if (voice) {+ await voice.ready;+ console.log(voice.status, voice.reason, voice.selection);+}+```++Keep the emitter for repeated triggers. It owns a definition lease and its own+choice stream; a fixed seed reproduces that emitter's sequence. Emitters for the+same canonical asset share event concurrency and cooldown, including across hot+reload generations. Event admission runs before clip IO, then the existing Audio+pool applies global priority and voice limits. Pending and paused requests hold+event slots. Cooldown begins at admission, including later load/global-limit+failures; stopping does not reset it. The Audio plugin advances its clock with+simulation time.++`ready` resolves when loading completes or is cancelled. `reason` distinguishes+event limits, cooldown, empty/disabled pools, global limits, missing positions and+load failures. Errors include the event and selected clip slot. Volume/rate controls,+pause and Stop remain valid during loading. Natural completion, Stop, global+`Audio.stopAll()`, owner despawn and App cleanup release the selected clip lease.+Dispose ownerless emitters explicitly with `emitter.dispose()`; owner-bound emitters+also dispose when their registry disconnects. `events.getStats()` reports admitted,+started, ended, stopped and rejected counts without storing trigger history.++Spatial events reuse AudioSource attenuation and panning; provide an owner with a+world transform or a position to `trigger()`. Without a listener the origin is used.+Mini-game hosts without stereo panning report that limitation while retaining+software distance attenuation. The dedicated event editor and component/visual-script+integration remain in RM-066.## `Audio` API referencediff --git a/docs/astro/src/content/docs/zh-cn/assets/audio.mdx b/docs/astro/src/content/docs/zh-cn/assets/audio.mdxindex fa38a74c2..2101cd847 100644--- a/docs/astro/src/content/docs/zh-cn/assets/audio.mdx+++ b/docs/astro/src/content/docs/zh-cn/assets/audio.mdx@@ -71,8 +71,36 @@ if (result.selection) {固定种子可重现片段及参数选择,不承诺后端采样同步;修改参数范围不会改变片段顺序。播放速率同时影响音高和时长,不是保时长变调。-选择器只负责选择片段和参数。定义也保存总线、优先级、空间衰减、事件并发上限和冷却设置,调用者负责在播放时应用。-事件级播放管理、专用制作界面、组件和可视化脚本接入仍在 RM-066 中继续实施。+选择器只负责选择片段和参数。使用托管播放资源,可以同时应用事件设置并管理加载和声音生命周期。++### 托管事件播放++```typescript+import { SoundEvents } from 'esengine';++const events = app.getResource(SoundEvents);+const emitter = await events.load('assets/steps.esaudioevent', { owner: entity, seed: 42 });+const voice = emitter?.trigger(); // 空间事件也可传入世界坐标。+if (voice) {+ await voice.ready;+ console.log(voice.status, voice.reason, voice.selection);+}+```++重复触发时保留发射器。它持有事件定义租约及独立选择序列,固定种子重现该发射器的序列。+同一资源的发射器共享事件并发与冷却,热更新前后的定义也共享名额。先检查事件准入,再加载选中的音频,+最后由现有 Audio 声音池应用全局优先级和声音上限。加载中和暂停的请求均占名额。+冷却从准入时开始,后续加载失败或全局池拒绝也不撤销冷却;停止不重置冷却。Audio 插件按模拟时间推进事件时钟。++`ready` 在加载完成或取消时返回状态;`reason` 区分事件上限、冷却、空池、全零权重、全局上限、缺少位置和加载失败。+加载错误包含事件路径及选中的槽位。加载期间也可修改音量/速率、暂停或停止。+自然结束、停止、全局 `Audio.stopAll()`、对象销毁和 App 清理均归还音频租约。+没有 owner 的发射器由调用者显式 `emitter.dispose()`;绑定对象的发射器在注册表断开时也会释放。+`events.getStats()` 记录准入、实际声音创建、结束、停止和拒绝数量,不保留触发历史。++空间事件复用 AudioSource 的衰减和声像计算,owner 需有世界变换,或在 `trigger()` 传入位置。+没有监听器时以原点为监听位置。小游戏宿主不支持立体声声像时会报告该限制,但仍应用软件距离衰减。+专用事件制作界面、组件和可视化脚本接入继续在 RM-066 中实施。## `Audio` API 参考diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 9f777d2ab..e8ad9f64d 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -2,11 +2,11 @@"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.","counts": {"public": 115,- "beta": 110,+ "beta": 117,"experimental": 2203,"deprecated": 3},- "total": 2428,+ "total": 2435,"subsystems": [{"id": "mobile-controls",@@ -2525,6 +2525,30 @@"minigame"]},+ {+ "name": "SoundEventEmitter",+ "kind": "interface",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },+ {+ "name": "SoundEventHandle",+ "kind": "interface",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },{"name": "SoundEventMode","kind": "type",@@ -2537,6 +2561,30 @@"minigame"]},+ {+ "name": "SoundEventPlayback",+ "kind": "class",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },+ {+ "name": "SoundEventRejection",+ "kind": "type",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },{"name": "SoundEventSelection","kind": "interface",@@ -2573,6 +2621,42 @@"minigame"]},+ {+ "name": "SoundEventStats",+ "kind": "interface",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },+ {+ "name": "SoundEventStatus",+ "kind": "type",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },+ {+ "name": "SoundEvents",+ "kind": "const",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },{"name": "SpawnOverride","kind": "type",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex e2287dfee..7d5195dd4 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: 115 public · 98 beta · 1581 experimental · 3 deprecated+Symbols: 115 public · 105 beta · 1581 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -8041,11 +8041,59 @@ clip: stringweight: number```+## SoundEventEmitter — interface @beta+```+dispose: () => void+disposed: boolean+ref: string+trigger: (position?: Vec3) => SoundEventHandle+```++## SoundEventHandle — interface @beta+```+currentTime: number+duration: number+error: string | null+id: number+isPlaying: boolean+onEnd: (() => void) | undefined+pause: () => void+ready: Promise<SoundEventStatus>+reason: SoundEventRejection | null+resume: () => void+selection: Readonly<SoundEventSelection> | null+setLoop: (loop: boolean) => void+setPan: (pan: number) => void+setPlaybackRate: (rate: number) => void+setVolume: (volume: number) => void+status: SoundEventStatus+stop: () => void+```+## SoundEventMode — type @beta```'random' | 'no-repeat' | 'sequence'```+## SoundEventPlayback — class @beta+```+@internal resetOwners: () => void+dispose: () => void+getStats: () => SoundEventStats+load: (ref: string, options?: { owner?: Entity; seed?: number; }) => Promise<SoundEventEmitter | null>+stopAll: () => void+stopOwner: (owner: Entity) => void+update: (delta: number, listener?: Vec3, right?: Vec3) => void+static new (audio: AudioAPI, resources: () => Resources | null, ownerAlive?: (owner: Entity) => boolean, ownerPosition?: (owner: Entity) => Vec3 | null): SoundEventPlayback+static prototype: SoundEventPlayback+```++## SoundEventRejection — type @beta+```+'disposed' | 'owner-gone' | 'cooldown' | 'event-limit'+ | 'empty' | 'zero-weight' | 'missing-position' | 'load-failed' | 'global-limit' | 'backend-refused'+```+## SoundEventSelection — interface @beta```clip: string@@ -8067,6 +8115,31 @@ static new (asset: SoundEventAsset, seed?: number): SoundEventSelectorstatic prototype: SoundEventSelector```+## SoundEventStats — interface @beta+```+active: number+admitted: number+definitions: number+emitters: number+ended: number+pendingClips: number+pendingDefinitions: number+played: number+reasons: Partial<Record<SoundEventRejection, number>>+rejected: number+stopped: number+```++## SoundEventStatus — type @beta+```+'loading' | 'playing' | 'paused' | 'ended' | 'stopped' | 'rejected'+```++## SoundEvents — const @beta+```+ResourceDef<SoundEventPlayback>+```+## SourceDelta — interface @experimental```added: readonly AddedEntity[]diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 72ce0b61a..8b64bb3df 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 103 beta · 1600 experimental · 3 deprecated+Symbols: 115 public · 110 beta · 1600 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -8254,11 +8254,59 @@ clip: stringweight: number```+## SoundEventEmitter — interface @beta+```+dispose: () => void+disposed: boolean+ref: string+trigger: (position?: Vec3) => SoundEventHandle+```++## SoundEventHandle — interface @beta+```+currentTime: number+duration: number+error: string | null+id: number+isPlaying: boolean+onEnd: (() => void) | undefined+pause: () => void+ready: Promise<SoundEventStatus>+reason: SoundEventRejection | null+resume: () => void+selection: Readonly<SoundEventSelection> | null+setLoop: (loop: boolean) => void+setPan: (pan: number) => void+setPlaybackRate: (rate: number) => void+setVolume: (volume: number) => void+status: SoundEventStatus+stop: () => void+```+## SoundEventMode — type @beta```'random' | 'no-repeat' | 'sequence'```+## SoundEventPlayback — class @beta+```+@internal resetOwners: () => void+dispose: () => void+getStats: () => SoundEventStats+load: (ref: string, options?: { owner?: Entity; seed?: number; }) => Promise<SoundEventEmitter | null>+stopAll: () => void+stopOwner: (owner: Entity) => void+update: (delta: number, listener?: Vec3, right?: Vec3) => void+static new (audio: AudioAPI, resources: () => Resources | null, ownerAlive?: (owner: Entity) => boolean, ownerPosition?: (owner: Entity) => Vec3 | null): SoundEventPlayback+static prototype: SoundEventPlayback+```++## SoundEventRejection — type @beta+```+'disposed' | 'owner-gone' | 'cooldown' | 'event-limit'+ | 'empty' | 'zero-weight' | 'missing-position' | 'load-failed' | 'global-limit' | 'backend-refused'+```+## SoundEventSelection — interface @beta```clip: string@@ -8280,6 +8328,31 @@ static new (asset: SoundEventAsset, seed?: number): SoundEventSelectorstatic prototype: SoundEventSelector```+## SoundEventStats — interface @beta+```+active: number+admitted: number+definitions: number+emitters: number+ended: number+pendingClips: number+pendingDefinitions: number+played: number+reasons: Partial<Record<SoundEventRejection, number>>+rejected: number+stopped: number+```++## SoundEventStatus — type @beta+```+'loading' | 'playing' | 'paused' | 'ended' | 'stopped' | 'rejected'+```++## SoundEvents — const @beta+```+ResourceDef<SoundEventPlayback>+```+## SourceDelta — interface @experimental```added: readonly AddedEntity[]diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 0b720e5ed..cedde2085 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: 115 public · 100 beta · 1580 experimental · 3 deprecated+Symbols: 115 public · 107 beta · 1580 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -8036,11 +8036,59 @@ clip: stringweight: number```+## SoundEventEmitter — interface @beta+```+dispose: () => void+disposed: boolean+ref: string+trigger: (position?: Vec3) => SoundEventHandle+```++## SoundEventHandle — interface @beta+```+currentTime: number+duration: number+error: string | null+id: number+isPlaying: boolean+onEnd: (() => void) | undefined+pause: () => void+ready: Promise<SoundEventStatus>+reason: SoundEventRejection | null+resume: () => void+selection: Readonly<SoundEventSelection> | null+setLoop: (loop: boolean) => void+setPan: (pan: number) => void+setPlaybackRate: (rate: number) => void+setVolume: (volume: number) => void+status: SoundEventStatus+stop: () => void+```+## SoundEventMode — type @beta```'random' | 'no-repeat' | 'sequence'```+## SoundEventPlayback — class @beta+```+@internal resetOwners: () => void+dispose: () => void+getStats: () => SoundEventStats+load: (ref: string, options?: { owner?: Entity; seed?: number; }) => Promise<SoundEventEmitter | null>+stopAll: () => void+stopOwner: (owner: Entity) => void+update: (delta: number, listener?: Vec3, right?: Vec3) => void+static new (audio: AudioAPI, resources: () => Resources | null, ownerAlive?: (owner: Entity) => boolean, ownerPosition?: (owner: Entity) => Vec3 | null): SoundEventPlayback+static prototype: SoundEventPlayback+```++## SoundEventRejection — type @beta+```+'disposed' | 'owner-gone' | 'cooldown' | 'event-limit'+ | 'empty' | 'zero-weight' | 'missing-position' | 'load-failed' | 'global-limit' | 'backend-refused'+```+## SoundEventSelection — interface @beta```clip: string@@ -8062,6 +8110,31 @@ static new (asset: SoundEventAsset, seed?: number): SoundEventSelectorstatic prototype: SoundEventSelector```+## SoundEventStats — interface @beta+```+active: number+admitted: number+definitions: number+emitters: number+ended: number+pendingClips: number+pendingDefinitions: number+played: number+reasons: Partial<Record<SoundEventRejection, number>>+rejected: number+stopped: number+```++## SoundEventStatus — type @beta+```+'loading' | 'playing' | 'paused' | 'ended' | 'stopped' | 'rejected'+```++## SoundEvents — const @beta+```+ResourceDef<SoundEventPlayback>+```+## SourceDelta — interface @experimental```added: readonly AddedEntity[]diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 777f73385..8baf03317 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 98 beta · 1602 experimental · 3 deprecated+Symbols: 115 public · 105 beta · 1602 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -8329,11 +8329,59 @@ clip: stringweight: number```+## SoundEventEmitter — interface @beta+```+dispose: () => void+disposed: boolean+ref: string+trigger: (position?: Vec3) => SoundEventHandle+```++## SoundEventHandle — interface @beta+```+currentTime: number+duration: number+error: string | null+id: number+isPlaying: boolean+onEnd: (() => void) | undefined+pause: () => void+ready: Promise<SoundEventStatus>+reason: SoundEventRejection | null+resume: () => void+selection: Readonly<SoundEventSelection> | null+setLoop: (loop: boolean) => void+setPan: (pan: number) => void+setPlaybackRate: (rate: number) => void+setVolume: (volume: number) => void+status: SoundEventStatus+stop: () => void+```+## SoundEventMode — type @beta```'random' | 'no-repeat' | 'sequence'```+## SoundEventPlayback — class @beta+```+@internal resetOwners: () => void+dispose: () => void+getStats: () => SoundEventStats+load: (ref: string, options?: { owner?: Entity; seed?: number; }) => Promise<SoundEventEmitter | null>+stopAll: () => void+stopOwner: (owner: Entity) => void+update: (delta: number, listener?: Vec3, right?: Vec3) => void+static new (audio: AudioAPI, resources: () => Resources | null, ownerAlive?: (owner: Entity) => boolean, ownerPosition?: (owner: Entity) => Vec3 | null): SoundEventPlayback+static prototype: SoundEventPlayback+```++## SoundEventRejection — type @beta+```+'disposed' | 'owner-gone' | 'cooldown' | 'event-limit'+ | 'empty' | 'zero-weight' | 'missing-position' | 'load-failed' | 'global-limit' | 'backend-refused'+```+## SoundEventSelection — interface @beta```clip: string@@ -8355,6 +8403,31 @@ static new (asset: SoundEventAsset, seed?: number): SoundEventSelectorstatic prototype: SoundEventSelector```+## SoundEventStats — interface @beta+```+active: number+admitted: number+definitions: number+emitters: number+ended: number+pendingClips: number+pendingDefinitions: number+played: number+reasons: Partial<Record<SoundEventRejection, number>>+rejected: number+stopped: number+```++## SoundEventStatus — type @beta+```+'loading' | 'playing' | 'paused' | 'ended' | 'stopped' | 'rejected'+```++## SoundEvents — const @beta+```+ResourceDef<SoundEventPlayback>+```+## SourceDelta — interface @experimental```added: readonly AddedEntity[]diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex babcc6ca7..5f7008e10 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 98 beta · 1593 experimental · 3 deprecated+Symbols: 115 public · 105 beta · 1593 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -8043,11 +8043,59 @@ clip: stringweight: number```+## SoundEventEmitter — interface @beta+```+dispose: () => void+disposed: boolean+ref: string+trigger: (position?: Vec3) => SoundEventHandle+```++## SoundEventHandle — interface @beta+```+currentTime: number+duration: number+error: string | null+id: number+isPlaying: boolean+onEnd: (() => void) | undefined+pause: () => void+ready: Promise<SoundEventStatus>+reason: SoundEventRejection | null+resume: () => void+selection: Readonly<SoundEventSelection> | null+setLoop: (loop: boolean) => void+setPan: (pan: number) => void+setPlaybackRate: (rate: number) => void+setVolume: (volume: number) => void+status: SoundEventStatus+stop: () => void+```+## SoundEventMode — type @beta```'random' | 'no-repeat' | 'sequence'```+## SoundEventPlayback — class @beta+```+@internal resetOwners: () => void+dispose: () => void+getStats: () => SoundEventStats+load: (ref: string, options?: { owner?: Entity; seed?: number; }) => Promise<SoundEventEmitter | null>+stopAll: () => void+stopOwner: (owner: Entity) => void+update: (delta: number, listener?: Vec3, right?: Vec3) => void+static new (audio: AudioAPI, resources: () => Resources | null, ownerAlive?: (owner: Entity) => boolean, ownerPosition?: (owner: Entity) => Vec3 | null): SoundEventPlayback+static prototype: SoundEventPlayback+```++## SoundEventRejection — type @beta+```+'disposed' | 'owner-gone' | 'cooldown' | 'event-limit'+ | 'empty' | 'zero-weight' | 'missing-position' | 'load-failed' | 'global-limit' | 'backend-refused'+```+## SoundEventSelection — interface @beta```clip: string@@ -8069,6 +8117,31 @@ static new (asset: SoundEventAsset, seed?: number): SoundEventSelectorstatic prototype: SoundEventSelector```+## SoundEventStats — interface @beta+```+active: number+admitted: number+definitions: number+emitters: number+ended: number+pendingClips: number+pendingDefinitions: number+played: number+reasons: Partial<Record<SoundEventRejection, number>>+rejected: number+stopped: number+```++## SoundEventStatus — type @beta+```+'loading' | 'playing' | 'paused' | 'ended' | 'stopped' | 'rejected'+```++## SoundEvents — const @beta+```+ResourceDef<SoundEventPlayback>+```+## SourceDelta — interface @experimental```added: readonly AddedEntity[]diff --git a/sdk/src/audio/AudioPlugin.ts b/sdk/src/audio/AudioPlugin.tsindex d5d5291a9..b300a95c4 100644--- a/sdk/src/audio/AudioPlugin.ts+++ b/sdk/src/audio/AudioPlugin.ts@@ -13,6 +13,9 @@ import { calculateAttenuation, calculatePanning, spatialDistance, type SpatialAuimport type { AudioHandle } from './PlatformAudioBackend';import { isEditor, isPlayMode } from '../ecs/env';import { log } from '../util/logger';+import { Assets } from '../asset/AssetPlugin';+import { SoundEvents, SoundEventPlayback } from './SoundEventPlayback';+import { disposeAll } from '../util/disposeAll';/*** Where a transform IS, which for a parented entity is not where it says it is:@@ -43,6 +46,8 @@ interface AudioPluginState {activeSourceHandles: Map<number, ActiveVoice>;playedEntities: Set<number>;audio: AudioAPI;+ events: SoundEventPlayback;+ offCoreDisconnect: () => void;released: boolean;offMemoryWarning: () => void;offAudioMute: () => void;@@ -79,6 +84,12 @@ export class AudioPlugin implements Plugin {const mixer = backend.mixer;const audio = new AudioAPI(backend, mixer);app.insertResource(Audio, audio);+ const events = new SoundEventPlayback(audio,+ () => app.hasResource(Assets) ? app.getResource(Assets) : null,+ owner => app.world.valid(owner) && (app.world.getCppRegistry()?.valid(owner) ?? true),+ owner => app.world.has(owner, WorldTransform) ? worldPositionOf(app.world.get(owner, WorldTransform)) : null);+ app.insertResource(SoundEvents, events);+ const offCoreDisconnect = app.world.onCoreDisconnect(() => events.resetOwners());const muteOwner = {};const offAudioMute = (isPlatformInitialized()? getPlatform().onAudioMute?.(muted => setAudioHostSuspended(audio, muteOwner, muted))@@ -104,13 +115,10 @@ export class AudioPlugin implements Plugin {const offDespawn = app.world.onDespawn((entity: Entity) => {const voice = activeSourceHandles.get(entity);- if (voice) {- voice.handle.stop();- activeSourceHandles.delete(entity);- }- playedEntities.delete(entity);+ activeSourceHandles.delete(entity); playedEntities.delete(entity);+ disposeAll([() => events.stopOwner(entity), () => voice?.handle.stop()], action => action());});- const state = { activeSourceHandles, playedEntities, audio, offMemoryWarning, offAudioMute, offExecution, offDespawn, released: false };+ const state = { activeSourceHandles, playedEntities, audio, events, offCoreDisconnect, offMemoryWarning, offAudioMute, offExecution, offDespawn, released: false };this.states_.set(app, state);this.latestState_ = state;const stopVoice = (id: number): void => {@@ -166,6 +174,7 @@ export class AudioPlugin implements Plugin {break;}}+ events.update(time.delta, listenerAt, listenerRight);const sources = world.getEntitiesWithComponents([AudioSource]);liveEntities.clear();@@ -316,9 +325,10 @@ export class AudioPlugin implements Plugin {}private stopSources_(state: AudioPluginState): void {- for (const voice of state.activeSourceHandles.values()) voice.handle.stop();+ const voices = [...state.activeSourceHandles.values()];state.activeSourceHandles.clear();state.playedEntities.clear();+ disposeAll(voices, voice => voice.handle.stop());}stopAllSources(): void {@@ -331,12 +341,8 @@ export class AudioPlugin implements Plugin {state.released = true;if (app) this.states_.delete(app);if (state === this.latestState_) this.latestState_ = null;- state.offAudioMute();- state.offExecution();- state.offMemoryWarning();- state.offDespawn();- this.stopSources_(state);- state.audio.dispose();+ disposeAll([state.offAudioMute, state.offExecution, state.offMemoryWarning, state.offDespawn, state.offCoreDisconnect,+ () => state.events.dispose(), () => this.stopSources_(state), () => state.audio.dispose()], action => action());}}diff --git a/sdk/src/audio/SoundEventPlayback.ts b/sdk/src/audio/SoundEventPlayback.tsnew file mode 100644index 000000000..3b80e2986--- /dev/null+++ b/sdk/src/audio/SoundEventPlayback.ts@@ -0,0 +1,313 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { Entity, Vec3 } from '../types';+import type { Assets } from '../asset/Assets';+import type { AssetLease } from '../asset/AssetLease';+import type { AudioResult } from '../asset/AssetLoader';+import { defineResource } from '../ecs/resource';+import { disposeAll } from '../util/disposeAll';+import type { AudioAPI } from './Audio';+import type { AudioHandle } from './PlatformAudioBackend';+import { parseSoundEvent, SoundEventSelector, type SoundEventAsset, type SoundEventSelection } from './SoundEvent';+import { calculateAttenuation, calculatePanning, spatialDistance } from './SpatialAudio';++/** Lifecycle of one admitted or rejected event trigger. @beta */+export type SoundEventStatus = 'loading' | 'playing' | 'paused' | 'ended' | 'stopped' | 'rejected';+/** Event gates run before clip loading; global admission runs through Audio. @beta */+export type SoundEventRejection = 'disposed' | 'owner-gone' | 'cooldown' | 'event-limit'+ | 'empty' | 'zero-weight' | 'missing-position' | 'load-failed' | 'global-limit' | 'backend-refused';+/** A trigger's controls remain valid while its selected clip loads. @beta */+export interface SoundEventHandle extends AudioHandle {+ readonly status: SoundEventStatus;+ readonly reason: SoundEventRejection | null;+ readonly error: string | null;+ readonly selection: Readonly<SoundEventSelection> | null;+ /** Initial loading resolves to its resulting status, including early cancellation. */+ readonly ready: Promise<SoundEventStatus>;+}+/** One owned definition and deterministic choice stream. Dispose to release its voices and definition. @beta */+export interface SoundEventEmitter {+ readonly ref: string;+ readonly disposed: boolean;+ /** Spatial events need an explicit world position or a live owner transform. */+ trigger(position?: Vec3): SoundEventHandle;+ dispose(): void;+}+/** Resource and admission counters, without retaining trigger history. @beta */+export interface SoundEventStats {+ definitions: number;+ emitters: number;+ pendingDefinitions: number;+ pendingClips: number;+ active: number;+ admitted: number;+ played: number;+ ended: number;+ stopped: number;+ rejected: number;+ reasons: Partial<Record<SoundEventRejection, number>>;+}++type Resources = Pick<Assets, 'acquireTyped'>;+interface SharedEvent { key: string; references: number; nextAllowed: number; active: Set<Request>; running: Set<Request> }+interface Emitter {+ ref: string; owner?: Entity; disposed: boolean; shared: SharedEvent; asset: SoundEventAsset;+ selector: SoundEventSelector; lease: AssetLease<SoundEventAsset>; resources: Resources; requests: Set<Request>;+}+interface Request {+ emitter: Emitter; generation: number; status: SoundEventStatus; reason: SoundEventRejection | null; error: string | null;+ selection: Readonly<SoundEventSelection> | null; native?: AudioHandle; lease?: AssetLease<AudioResult>;+ paused: boolean; loop: boolean; volume: number; rate: number; pan: number; position?: Vec3;+ lastVolume?: number; lastPan?: number;+ resolve(status: SoundEventStatus): void; onEnd?: () => void;+}+interface PendingDefinition { owner?: Entity; cancelled: boolean }++/** Per-App event ownership layered on Assets leases and Audio's existing voice pool.+ * Emitters of one canonical definition share admission across asset generations.+ * Cooldown starts on admission, including later load/global-pool failures; stopping does not reset it.+ * @beta */+export class SoundEventPlayback {+ private readonly events = new Map<string, SharedEvent>();+ private readonly emitters = new Set<Emitter>();+ private readonly pending = new Set<PendingDefinition>();+ private readonly owners = new Map<Entity, Set<Emitter>>();+ private readonly ownerLoads = new Map<Entity, Set<PendingDefinition>>();+ private readonly reasons: Partial<Record<SoundEventRejection, number>> = {};+ private readonly offStop: () => void;+ private clock = 0;+ private disposed = false;+ private admitted = 0;+ private played = 0;+ private ended = 0;+ private stopped = 0;+ private rejected = 0;+ private listener: Vec3 = { x: 0, y: 0, z: 0 };+ private right: Vec3 = { x: 1, y: 0, z: 0 };++ constructor(private readonly audio: AudioAPI, private readonly resources: () => Resources | null,+ private readonly ownerAlive: (owner: Entity) => boolean = () => true,+ private readonly ownerPosition: (owner: Entity) => Vec3 | null = () => null) {+ this.offStop = audio.onPlaybackStop(generation => {+ const requests = [...this.events.values()].flatMap(event => [...event.active]).filter(request => request.generation < generation);+ disposeAll(requests, request => this.finish(request, 'stopped', false));+ });+ }++ /** Loading a definition is preparation, not a play intent; Audio.stopAll does not unload emitters. */+ async load(ref: string, options: { owner?: Entity; seed?: number } = {}): Promise<SoundEventEmitter | null> {+ if (this.disposed || (options.owner !== undefined && !this.ownerAlive(options.owner))) return null;+ const resources = this.resources();+ if (!resources) throw new Error(`${ref}: no Assets resource for sound events`);+ const pending: PendingDefinition = { owner: options.owner, cancelled: false };+ this.pending.add(pending);+ if (pending.owner !== undefined) this.addOwner(this.ownerLoads, pending.owner, pending);+ let lease: AssetLease<SoundEventAsset> | undefined;+ try {+ lease = await resources.acquireTyped<SoundEventAsset>('sound-event', ref);+ if (this.disposed || pending.cancelled || resources !== this.resources()+ || (pending.owner !== undefined && !this.ownerAlive(pending.owner))) { lease.release(); return null; }+ const asset = parseSoundEvent(lease.value);+ const selector = new SoundEventSelector(asset, options.seed ?? (Math.random() * 4294967296) >>> 0);+ let shared = this.events.get(lease.key);+ if (!shared) { shared = { key: lease.key, references: 0, nextAllowed: 0, active: new Set(), running: new Set() }; this.events.set(lease.key, shared); }+ const emitter: Emitter = { ref, owner: options.owner, disposed: false, shared, asset, selector, lease, resources, requests: new Set() };+ shared.references++; this.emitters.add(emitter);+ if (emitter.owner !== undefined) this.addOwner(this.owners, emitter.owner, emitter);+ return { ref, get disposed() { return emitter.disposed; }, trigger: position => this.trigger(emitter, position),+ dispose: () => this.releaseEmitter(emitter) };+ } catch (error) {+ lease?.release();+ if (this.disposed || pending.cancelled || resources !== this.resources()+ || (pending.owner !== undefined && !this.ownerAlive(pending.owner))) return null;+ throw error;+ } finally {+ this.pending.delete(pending);+ if (pending.owner !== undefined) this.removeOwner(this.ownerLoads, pending.owner, pending);+ }+ }++ /** Advance on simulation time; paused requests retain event and global voice ownership. */+ update(delta: number, listener?: Vec3, right?: Vec3): void {+ if (this.disposed) return;+ if (Number.isFinite(delta) && delta > 0) this.clock += delta;+ if (listener) this.listener = { ...listener };+ if (right) this.right = { ...right };+ for (const emitter of [...this.emitters]) {+ if (emitter.resources !== this.resources()) { this.releaseEmitter(emitter); continue; }+ if (emitter.owner !== undefined && !this.ownerAlive(emitter.owner)) { this.releaseEmitter(emitter); continue; }+ for (const request of [...emitter.requests]) { this.refresh(request); this.applySpatial(request); }+ }+ }++ stopOwner(owner: Entity): void {+ for (const pending of this.ownerLoads.get(owner) ?? []) pending.cancelled = true;+ disposeAll([...(this.owners.get(owner) ?? [])], emitter => this.releaseEmitter(emitter));+ }++ /** @internal A registry switch cannot transfer an old entity owner's emitters to reused IDs. */+ resetOwners(): void {+ const owners = new Set([...this.ownerLoads.keys(), ...this.owners.keys()]);+ disposeAll([...owners], owner => this.stopOwner(owner));+ }++ stopAll(): void {+ const active = [...this.events.values()].flatMap(event => [...event.active]);+ disposeAll(active, request => this.finish(request, 'stopped', true));+ }++ getStats(): SoundEventStats {+ let pendingClips = 0, active = 0;+ for (const event of this.events.values()) for (const request of [...event.active]) {+ this.refresh(request);+ if (this.live(request)) { active++; if (!request.native) pendingClips++; }+ }+ return { definitions: this.events.size, emitters: this.emitters.size, pendingDefinitions: this.pending.size,+ pendingClips, active, admitted: this.admitted, played: this.played, ended: this.ended, stopped: this.stopped,+ rejected: this.rejected, reasons: { ...this.reasons } };+ }++ dispose(): void {+ if (this.disposed) return;+ this.disposed = true; this.offStop();+ for (const pending of this.pending) pending.cancelled = true;+ this.pending.clear(); this.ownerLoads.clear();+ disposeAll([...this.emitters], emitter => this.releaseEmitter(emitter));+ }++ private addOwner<T>(map: Map<Entity, Set<T>>, owner: Entity, value: T): void {+ let entries = map.get(owner); if (!entries) { entries = new Set(); map.set(owner, entries); } entries.add(value);+ }+ private removeOwner<T>(map: Map<Entity, Set<T>>, owner: Entity, value: T): void {+ const entries = map.get(owner); entries?.delete(value); if (!entries?.size) map.delete(owner);+ }+ private live(request: Request): boolean { return request.status === 'loading' || request.status === 'playing' || request.status === 'paused'; }+ private refresh(request: Request): void {+ if (!this.live(request) || !request.native) return;+ const state = this.audio.getVoiceState(request.native);+ if (state === 'stopped' || state === 'untracked') this.finish(request, 'stopped', false);+ else if (state === 'ended') this.end(request);+ else request.status = state;+ }+ private end(request: Request): void {+ if (!this.live(request)) return;+ const callback = request.onEnd;+ try { this.finish(request, 'ended', false); } finally { callback?.(); }+ }+ private finish(request: Request, status: SoundEventStatus, stop: boolean): void {+ if (!this.live(request)) return;+ request.status = status; request.resolve(status);+ if (status === 'ended') this.ended++; else if (status === 'stopped') this.stopped++;+ request.emitter.requests.delete(request); request.emitter.shared.active.delete(request);+ request.emitter.shared.running.delete(request);+ const native = request.native, lease = request.lease; request.lease = undefined;+ disposeAll([() => { if (native) native.onEnd = undefined; }, () => { if (stop) native?.stop(); }, () => lease?.release()], action => action());+ }+ private reject(request: Request, reason: SoundEventRejection, error?: string): void {+ request.reason = reason; request.error = error ?? null; this.rejected++;+ this.reasons[reason] = (this.reasons[reason] ?? 0) + 1;+ this.finish(request, 'rejected', !!request.native);+ }+ private releaseEmitter(emitter: Emitter): void {+ if (emitter.disposed) return;+ emitter.disposed = true; this.emitters.delete(emitter);+ if (emitter.owner !== undefined) this.removeOwner(this.owners, emitter.owner, emitter);+ try { disposeAll([...emitter.requests], request => this.finish(request, 'stopped', true)); }+ finally {+ if (--emitter.shared.references === 0) this.events.delete(emitter.shared.key);+ emitter.lease.release();+ }+ }++ private trigger(emitter: Emitter, position?: Vec3): SoundEventHandle {+ if (!emitter.disposed && emitter.resources !== this.resources()) this.releaseEmitter(emitter);+ let resolve!: (status: SoundEventStatus) => void;+ const ready = new Promise<SoundEventStatus>(done => { resolve = done; });+ const request: Request = { emitter, generation: this.audio.playbackGeneration, status: 'loading', reason: null, error: null,+ selection: null, paused: false, loop: false, volume: 1, rate: 1, pan: 0, position: position ? { ...position } : undefined, resolve };+ const handle: SoundEventHandle = {+ ready, get id() { return request.native?.id ?? -1; },+ get status() { refresh(); return request.status; }, get reason() { return request.reason; }, get error() { return request.error; },+ get selection() { return request.selection; }, get isPlaying() { refresh(); return request.status === 'playing'; },+ get duration() { return request.native?.duration ?? 0; }, get currentTime() { return request.native?.currentTime ?? 0; },+ stop: () => this.finish(request, 'stopped', true),+ pause: () => { refresh(); if (this.live(request)) { request.paused = true; request.native?.pause(); refresh(); } },+ resume: () => { refresh(); if (this.live(request)) { request.paused = false; request.native?.resume(); refresh(); } },+ setVolume: volume => { if (this.live(request)) { request.volume = volume; this.applySpatial(request); } },+ setPan: pan => { if (this.live(request)) { request.pan = pan; this.applySpatial(request); } },+ setLoop: loop => { if (this.live(request)) { request.loop = loop; request.native?.setLoop(loop); } },+ setPlaybackRate: rate => { if (this.live(request)) { request.rate = rate; request.native?.setPlaybackRate(rate); } },+ get onEnd() { return request.onEnd; }, set onEnd(callback) { request.onEnd = callback; },+ };+ const refresh = () => this.refresh(request);+ if (this.disposed || emitter.disposed || emitter.resources !== this.resources()) this.reject(request, 'disposed');+ else if (emitter.owner !== undefined && !this.ownerAlive(emitter.owner)) this.reject(request, 'owner-gone');+ else if (emitter.asset.spatial && !this.position(request)) this.reject(request, 'missing-position');+ else {+ // Pending requests already own counted slots; only started voices can have retired externally.+ for (const existing of [...emitter.shared.running]) this.refresh(existing);+ if (this.clock < emitter.shared.nextAllowed) this.reject(request, 'cooldown');+ else if (emitter.asset.maxInstances > 0 && emitter.shared.active.size >= emitter.asset.maxInstances) this.reject(request, 'event-limit');+ else {+ const result = emitter.selector.next();+ if (!result.selection) this.reject(request, result.reason);+ else {+ request.selection = Object.freeze(result.selection); request.volume = result.selection.volume; request.rate = result.selection.playbackRate;+ emitter.shared.nextAllowed = this.clock + emitter.asset.cooldown;+ emitter.requests.add(request); emitter.shared.active.add(request); this.admitted++;+ void this.start(request);+ }+ }+ }+ return handle;+ }++ private position(request: Request): Vec3 | null {+ const position = request.position ?? (request.emitter.owner !== undefined ? this.ownerPosition(request.emitter.owner) : null);+ return position && Number.isFinite(position.x) && Number.isFinite(position.y) && Number.isFinite(position.z) ? position : null;+ }+ private applySpatial(request: Request): void {+ if (!request.native || !this.live(request)) return;+ const spatial = request.emitter.asset.spatial, position = this.position(request);+ if (spatial && !position) { this.reject(request, 'missing-position'); return; }+ const volume = request.volume * (spatial && position ? calculateAttenuation(spatialDistance(position, this.listener), spatial) : 1);+ if (volume !== request.lastVolume) { request.native.setVolume(volume); request.lastVolume = volume; }+ const pan = Math.max(-1, Math.min(1, request.pan + (spatial && position ? calculatePanning(position, this.listener, this.right, spatial.maxDistance) : 0)));+ if (pan !== request.lastPan && (pan !== 0 || request.lastPan !== undefined || spatial)) {+ request.native.setPan(pan); request.lastPan = pan;+ }+ }+ private async start(request: Request): Promise<void> {+ const { emitter, selection } = request;+ try {+ const lease = await emitter.resources.acquireTyped<AudioResult>('audio', selection!.clip);+ if (!this.live(request)) { lease.release(); return; }+ request.lease = lease;+ if (this.disposed || emitter.disposed || emitter.resources !== this.resources()) { this.finish(request, 'stopped', false); return; }+ if (emitter.owner !== undefined && !this.ownerAlive(emitter.owner)) { this.reject(request, 'owner-gone'); return; }+ if (emitter.asset.spatial && !this.position(request)) { this.reject(request, 'missing-position'); return; }+ const buffer = this.audio.getBufferHandle(lease.value.bufferId);+ if (!buffer) throw new Error('selected audio buffer is unavailable');+ const native = this.audio.playBuffer(buffer, { bus: emitter.asset.bus, priority: emitter.asset.priority,+ volume: 0, playbackRate: request.rate, loop: request.loop });+ if (!this.live(request)) { native.stop(); return; }+ request.native = native;+ const state = this.audio.getVoiceState(native);+ if (state === 'untracked') { this.reject(request, 'global-limit'); return; }+ if (state === 'ended' || state === 'stopped') { this.reject(request, 'backend-refused'); return; }+ emitter.shared.running.add(request);+ for (const existing of [...emitter.shared.running]) this.refresh(existing);+ if (!this.live(request)) return;+ this.played++;+ native.onEnd = () => this.end(request);+ if (request.paused) native.pause();+ request.status = this.audio.getVoiceState(native) === 'paused' ? 'paused' : 'playing';+ this.applySpatial(request); request.resolve(request.status);+ } catch (error) {+ if (this.live(request)) this.reject(request, 'load-failed', `${emitter.ref}: clips[${selection!.slot}].clip (${selection!.clip}): ${String(error)}`);+ }+ }+}++/** Per-App sound event loading, emitters and admission controls. @beta */+export const SoundEvents = defineResource<SoundEventPlayback>(null!, 'SoundEvents');diff --git a/sdk/src/audio/index.ts b/sdk/src/audio/index.tsindex 1c538bcb8..78f3ee9a9 100644--- a/sdk/src/audio/index.ts+++ b/sdk/src/audio/index.ts@@ -1,6 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamexport { Audio, AudioAPI, type AudioBufferStats } from './Audio';+export { SoundEvents, SoundEventPlayback, type SoundEventEmitter, type SoundEventHandle,+ type SoundEventStatus, type SoundEventRejection, type SoundEventStats } from './SoundEventPlayback';export { parseSoundEvent, SoundEventSelector, type SoundEventAsset, type SoundEventClip,type SoundEventMode, type SoundEventSelection, type SoundEventSelectionResult } from './SoundEvent';export { AudioBus, type AudioBusConfig } from './AudioBus';diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 22b600551..935095c83 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -661,6 +661,13 @@ export {parseAudioProjectConfig,parseSoundEvent,SoundEventSelector,+ SoundEvents,+ SoundEventPlayback,+ type SoundEventEmitter,+ type SoundEventHandle,+ type SoundEventStatus,+ type SoundEventRejection,+ type SoundEventStats,type SoundEventAsset,type SoundEventClip,type SoundEventMode,diff --git a/sdk/tests/audio-plugin-lifecycle.test.ts b/sdk/tests/audio-plugin-lifecycle.test.tsindex c208ffa3c..d2c7b453e 100644--- a/sdk/tests/audio-plugin-lifecycle.test.ts+++ b/sdk/tests/audio-plugin-lifecycle.test.ts@@ -29,6 +29,9 @@ const { App } = await import('../src/app/app');const { AudioPlugin } = await import('../src/audio/AudioPlugin');const { Audio } = await import('../src/audio/Audio');const { AudioSource } = await import('../src/audio/AudioComponents');+const { SoundEvents } = await import('../src/audio/SoundEventPlayback');+const { Assets } = await import('../src/asset/AssetPlugin');+const { parseSoundEvent } = await import('../src/audio/SoundEvent');const apps: ReturnType<typeof App.new>[] = [];function build(plugin: InstanceType<typeof AudioPlugin>) { const app=App.new(); apps.push(app); app.addPlugin(plugin); return app; }afterEach(() => { for(const app of apps.splice(0)) app.quit(); backends.length=0; listeners.clear(); muteListeners.clear(); hostMuted=false; });@@ -98,3 +101,24 @@ it('stopAllSources silences the latest source and resets its playOnAwake triggerplugin.stopAllSources(); expect(old.isPlaying).toBe(false);await app.tick(1/60); expect(backends[0].play).toHaveBeenCalledTimes(2);});++it('installs per-app event ownership and releases an emitter when its entity despawns', async () => {+ const plugin = new AudioPlugin(), app = build(plugin), owner = app.world.spawn(), release = vi.fn();+ const lease = { key: 'steps', generation: 1, value: parseSoundEvent({ version: 1, clips: [] }), release, retain: () => null };+ app.insertResource(Assets, { acquireTyped: vi.fn().mockResolvedValue(lease) } as unknown as import('../src/asset/Assets').Assets);+ const events = app.getResource(SoundEvents), emitter = (await events.load('steps.esaudioevent', { owner }))!;+ app.world.despawn(owner); expect(emitter.disposed).toBe(true); expect(release).toHaveBeenCalledOnce();+ expect(events.getStats().emitters).toBe(0); app.quit(); expect(app.world.getStorageSizes().coreDisconnectCallbacks).toBe(0);+});++it('registry disconnect releases entity event owners and late definition loads cannot cross app quit', async () => {+ const app = build(new AudioPlugin()), owner = app.world.spawn(), release = vi.fn();+ const lease = { key: 'steps', generation: 1, value: parseSoundEvent({ version: 1, clips: [] }), release, retain: () => null };+ let resolve!: (value: typeof lease) => void;+ const acquire = vi.fn().mockResolvedValueOnce(lease).mockImplementationOnce(() => new Promise(done => { resolve = done; }));+ app.insertResource(Assets, { acquireTyped: acquire } as unknown as import('../src/asset/Assets').Assets);+ const events = app.getResource(SoundEvents), emitter = (await events.load('steps.esaudioevent', { owner }))!;+ app.world.disconnectCpp(); expect(emitter.disposed).toBe(true); expect(release).toHaveBeenCalledOnce();+ const pending = events.load('later.esaudioevent'); app.quit(); resolve(lease);+ expect(await pending).toBeNull(); expect(release).toHaveBeenCalledTimes(2);+});diff --git a/sdk/tests/sound-event-playback.test.ts b/sdk/tests/sound-event-playback.test.tsnew file mode 100644index 000000000..ac050861c--- /dev/null+++ b/sdk/tests/sound-event-playback.test.ts@@ -0,0 +1,217 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, describe, expect, it, vi } from 'vitest';+vi.mock('../src/wasm/resourceManager', () => ({ requireResourceManager: () => ({}), getResourceManager: () => null, evictTextureDimensions: vi.fn() }));+import { AudioAPI } from '../src/audio/Audio';+import type { AudioHandle, AudioBufferHandle, PlatformAudioBackend, PlayConfig } from '../src/audio/PlatformAudioBackend';+import { Assets } from '../src/asset/Assets';+import type { Backend } from '../src/asset/Backend';+import { SoundEventPlayback } from '../src/audio/SoundEventPlayback';+import { MiniGameAudioBackend } from '../src/audio/MiniGameAudioBackend';+import type { MiniGameGlobal, MiniGameInnerAudioContext } from '../src/platform/minigame/api';+import type { Entity } from '../src/types';++const cleanup: Array<() => void> = [];+afterEach(() => { for (const close of cleanup.splice(0)) close(); vi.restoreAllMocks(); });+function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>(done => { resolve = done; }); return { promise, resolve }; }++function fixture(extra: Record<string, unknown> = {}, actualBackend?: PlatformAudioBackend) {+ let id = 0;+ const voices: Array<{ handle: AudioHandle; end(): void; config: PlayConfig }> = [];+ const backend = {+ name: 'counting', mixer: null, isReady: true, delivery: 'bytes' as const,+ initialize: vi.fn(async () => {}), ensureResumed: vi.fn(async () => {}),+ loadBuffer: vi.fn(async () => ({ id: ++id, bytes: 4, duration: 1 })),+ loadBufferFromData: vi.fn(async () => ({ id: ++id, bytes: 4, duration: 1 })), unloadBuffer: vi.fn(),+ suspend: vi.fn(), resume: vi.fn(), dispose: vi.fn(),+ play: vi.fn((_buffer: AudioBufferHandle, config: PlayConfig = {}): AudioHandle => {+ let playing = true, stopped = false;+ const handle: AudioHandle = { id: ++id, currentTime: 0, duration: 1,+ get isPlaying() { return playing; },+ stop: vi.fn(() => { playing = false; stopped = true; }), pause: vi.fn(() => { playing = false; }),+ resume: vi.fn(() => { if (!stopped) playing = true; }), setVolume: vi.fn(), setPan: vi.fn(),+ setLoop: vi.fn(), setPlaybackRate: vi.fn(),+ };+ voices.push({ handle, config, end() { playing = false; handle.onEnd?.(); } }); return handle;+ }),+ } satisfies PlatformAudioBackend;+ const audio = new AudioAPI(actualBackend ?? backend); audio.setBufferBudget(0);+ let document: Record<string, unknown> = { version: 1, mode: 'sequence', clips: [{ clip: 'a.wav' }, { clip: 'b.wav' }], ...extra };+ const fetchText = vi.fn(async () => JSON.stringify(document));+ const fetchBinary = vi.fn(async () => new ArrayBuffer(4));+ const resources = Assets.create({ module: null, getAudio: () => audio, backend: { fetchText, fetchBinary,+ resolveUrl: (ref: string) => ref, setBaseUrl() {} } as unknown as Backend });+ const alive = new Set<Entity>(), positions = new Map<Entity, { x: number; y: number; z: number }>();+ const events = new SoundEventPlayback(audio, () => resources, owner => alive.has(owner), owner => positions.get(owner) ?? null);+ cleanup.push(() => { events.dispose(); resources.releaseAll(); audio.dispose(); });+ return { events, audio, backend, voices, resources, alive, positions, fetchText, fetchBinary,+ setDocument: (next: typeof document) => { document = next; } };+}++describe('event admission and owned playback', () => {+ it('loads definitions without fetching clips and releases its definition on emitter disposal', async () => {+ const { events, fetchBinary } = fixture(); const emitter = (await events.load('steps.esaudioevent', { seed: 1 }))!;+ expect(fetchBinary).not.toHaveBeenCalled(); expect(events.getStats().emitters).toBe(1);+ emitter.dispose(); emitter.dispose(); expect(events.getStats()).toMatchObject({ definitions: 0, emitters: 0, active: 0 });+ expect(emitter.trigger().reason).toBe('disposed');+ });++ it('holds one event slot through loading and pause, then frees it on natural completion', async () => {+ const { events, fetchBinary, voices, audio } = fixture({ maxInstances: 1 });+ const load = deferred<ArrayBuffer>(); fetchBinary.mockReturnValue(load.promise);+ const emitter = (await events.load('steps.esaudioevent'))!, first = emitter.trigger(); first.pause();+ expect(emitter.trigger().reason).toBe('event-limit'); expect(events.getStats().pendingClips).toBe(1);+ load.resolve(new ArrayBuffer(4)); expect(await first.ready).toBe('paused');+ expect(emitter.trigger().reason).toBe('event-limit'); first.resume(); expect(first.status).toBe('playing');+ const ended = vi.fn(); first.onEnd = ended; voices[0].end();+ expect(first.status).toBe('ended'); expect(ended).toHaveBeenCalledOnce();+ expect(audio.getBufferStats().bufferCount).toBe(0);+ expect(await emitter.trigger().ready).toBe('playing');+ });++ it('shares event limits and cooldown across emitters without advancing rejected choices', async () => {+ const { events, backend } = fixture({ maxInstances: 1, cooldown: .5 });+ const a = (await events.load('steps.esaudioevent', { seed: 4 }))!, b = (await events.load('steps.esaudioevent', { seed: 4 }))!;+ const first = a.trigger(); await first.ready;+ expect(b.trigger().reason).toBe('cooldown'); first.stop(); expect(a.trigger().reason).toBe('cooldown');+ events.update(.5); const second = a.trigger(); expect(second.selection?.clip).toBe('b.wav'); await second.ready;+ events.update(.5); expect(b.trigger().reason).toBe('event-limit'); expect(backend.play).toHaveBeenCalledTimes(2);+ });++ it('uses global priority admission and releases clips after refusal or stealing a paused voice', async () => {+ const { events, audio, backend } = fixture({ maxInstances: 1, priority: 2 }); audio.setMaxVoices(1);+ const buffer = { id: 900, duration: 1 }; const high = audio.playBuffer(buffer, { priority: 9 });+ const emitter = (await events.load('steps.esaudioevent'))!;+ const rejected = emitter.trigger(); expect(await rejected.ready).toBe('rejected'); expect(rejected.reason).toBe('global-limit');+ expect(events.getStats().active).toBe(0); high.stop();+ const first = emitter.trigger(); await first.ready; first.pause();+ audio.playBuffer(buffer, { priority: 9 }); expect(first.status).toBe('stopped');+ expect(events.getStats().active).toBe(0); expect(backend.play).toHaveBeenCalledTimes(3);+ });++ it('cancels pending clips synchronously on Audio.stopAll and cannot resume them later', async () => {+ const { events, audio, fetchBinary, backend } = fixture({ maxInstances: 1 });+ const load = deferred<ArrayBuffer>(); fetchBinary.mockReturnValue(load.promise);+ const emitter = (await events.load('steps.esaudioevent'))!, pending = emitter.trigger();+ audio.stopAll(); expect(await pending.ready).toBe('stopped'); expect(events.getStats().active).toBe(0);+ pending.resume(); load.resolve(new ArrayBuffer(4)); await new Promise(done => setTimeout(done, 0));+ expect(backend.play).not.toHaveBeenCalled(); expect(audio.getBufferStats().bufferCount).toBe(0);+ expect(await emitter.trigger().ready).toBe('playing');+ });++ it('cancels owner definition and clip loads and returns every late lease', async () => {+ const { events, fetchText, fetchBinary, alive, backend } = fixture(); const owner = 123 as Entity; alive.add(owner);+ const definition = deferred<string>(); fetchText.mockReturnValueOnce(definition.promise);+ const loading = events.load('steps.esaudioevent', { owner }); events.stopOwner(owner); alive.delete(owner);+ definition.resolve(JSON.stringify({ version: 1, clips: [] })); expect(await loading).toBeNull();+ alive.add(owner); const emitter = (await events.load('other.esaudioevent', { owner }))!;+ const clip = deferred<ArrayBuffer>(); fetchBinary.mockReturnValueOnce(clip.promise);+ const pending = emitter.trigger(); events.stopOwner(owner); expect(await pending.ready).toBe('stopped');+ clip.resolve(new ArrayBuffer(4)); await new Promise(done => setTimeout(done, 0));+ expect(backend.play).not.toHaveBeenCalled(); expect(events.getStats()).toMatchObject({ definitions: 0, emitters: 0, active: 0 });+ });++ it('reports a missing selected resource by event, slot and clip without leaking an event slot', async () => {+ const { events, fetchBinary } = fixture({ clips: [{ clip: 'missing.wav' }], maxInstances: 1 });+ fetchBinary.mockRejectedValue(new Error('404'));+ const emitter = (await events.load('steps.esaudioevent'))!, request = emitter.trigger();+ expect(await request.ready).toBe('rejected'); expect(request.reason).toBe('load-failed');+ expect(request.error).toContain('steps.esaudioevent: clips[0].clip (missing.wav)');+ expect(events.getStats()).toMatchObject({ active: 0, played: 0, rejected: 1, reasons: { 'load-failed': 1 } });+ });++ it('applies bus gain and sampled rates through the existing AudioAPI', async () => {+ const { events, audio, voices } = fixture({ bus: 'ui', volume: [.4, .4], playbackRate: [1.3, 1.3], priority: 7 });+ audio.setUIVolume(.5); const emitter = (await events.load('click.esaudioevent'))!, request = emitter.trigger();+ await request.ready; expect(voices[0].config).toMatchObject({ bus: 'ui', playbackRate: 1.3, priority: 7, volume: 0 });+ expect(voices[0].handle.setVolume).toHaveBeenLastCalledWith(.2);+ request.setVolume(.8); expect(voices[0].handle.setVolume).toHaveBeenLastCalledWith(.4);+ });++ it('updates spatial attenuation from the owning entity and refuses absent world positions', async () => {+ const { events, alive, positions, voices } = fixture({ spatial: { model: 1, refDistance: 10, maxDistance: 1000, rolloff: 1 } });+ const owner = 9 as Entity; alive.add(owner); positions.set(owner, { x: 20, y: 0, z: 0 });+ const unowned = (await events.load('space.esaudioevent'))!; expect(unowned.trigger().reason).toBe('missing-position');+ const emitter = (await events.load('space.esaudioevent', { owner }))!; await emitter.trigger().ready;+ expect(voices[0].handle.setVolume).toHaveBeenLastCalledWith(.5);+ positions.set(owner, { x: 40, y: 0, z: 0 }); events.update(.1);+ expect(voices[0].handle.setVolume).toHaveBeenLastCalledWith(.25);+ alive.delete(owner); events.update(.1); expect(emitter.disposed).toBe(true);+ expect(events.getStats().active).toBe(0);+ });++ it.each([{ clips: [] }, { clips: [{ clip: 'a.wav', weight: 0 }] }])('does no clip IO for unavailable pools %j', async ({ clips }) => {+ const { events, fetchBinary } = fixture({ clips }); const emitter = (await events.load('empty.esaudioevent'))!;+ expect(await emitter.trigger().ready).toBe('rejected'); expect(fetchBinary).not.toHaveBeenCalled();+ expect(events.getStats().active).toBe(0);+ });++ it('does not resurrect a voice when Stop All runs synchronously inside backend play', async () => {+ const { events, backend, audio, voices } = fixture(); const play = backend.play.getMockImplementation()!;+ backend.play.mockImplementation((buffer, config) => { const handle = play(buffer, config); audio.stopAll(); return handle; });+ const emitter = (await events.load('steps.esaudioevent'))!, request = emitter.trigger();+ expect(await request.ready).toBe('stopped'); await new Promise(done => setTimeout(done, 0));+ expect(voices[0].handle.isPlaying).toBe(false); expect(events.getStats().active).toBe(0);+ });++ it('shares admission across hot-reloaded generations while each emitter keeps its own definition', async () => {+ const { events, resources, setDocument } = fixture({ maxInstances: 1 });+ const old = (await events.load('steps.esaudioevent'))!, first = old.trigger(); await first.ready;+ setDocument({ version: 1, clips: [{ clip: 'new.wav' }], maxInstances: 1 }); resources.invalidate('steps.esaudioevent');+ const next = (await events.load('steps.esaudioevent'))!;+ expect(events.getStats().definitions).toBe(1); expect(next.trigger().reason).toBe('event-limit');+ first.stop(); const changed = next.trigger(); expect(changed.selection?.clip).toBe('new.wav'); await changed.ready;+ old.dispose(); expect(events.getStats().active).toBe(1); next.dispose(); expect(events.getStats().definitions).toBe(0);+ });++ it('drains every receipt and count even if one release fails', async () => {+ const { events, resources, audio } = fixture();+ const acquire = resources.acquireTyped.bind(resources);+ resources.acquireTyped = async <T>(type: string, ref: string) => {+ const lease = await acquire<T>(type, ref);+ return type !== 'audio' ? lease : { ...lease, release() { lease.release(); throw new Error('release failed'); } };+ };+ const emitter = (await events.load('steps.esaudioevent'))!;+ await Promise.all([emitter.trigger().ready, emitter.trigger().ready]);+ expect(() => events.stopAll()).toThrow('release failed');+ expect(events.getStats().active).toBe(0); expect(audio.getBufferStats().bufferCount).toBe(0);+ });++ it('withdraws all event ownership when a backend stop throws', async () => {+ const { events, voices, audio } = fixture(); const emitter = (await events.load('steps.esaudioevent'))!;+ const requests = [emitter.trigger(), emitter.trigger()]; await Promise.all(requests.map(request => request.ready));+ vi.mocked(voices[0].handle.stop).mockImplementation(() => { throw new Error('stop failed'); });+ expect(() => audio.stopAll()).toThrow('stop failed');+ expect(requests.map(request => request.status)).toEqual(['stopped', 'stopped']);+ expect(voices[1].handle.isPlaying).toBe(false); expect(events.getStats().active).toBe(0);+ expect(audio.getBufferStats().bufferCount).toBe(0);+ });++ it('cancels a dense pending burst without starting late audio or retaining decoded buffers', async () => {+ const { events, fetchBinary, backend, audio } = fixture(); const clip = deferred<ArrayBuffer>(); fetchBinary.mockReturnValue(clip.promise);+ const emitter = (await events.load('steps.esaudioevent'))!;+ for (let i = 0; i < 512; ++i) emitter.trigger();+ await new Promise(done => setTimeout(done, 0));+ expect(events.getStats()).toMatchObject({ active: 512, pendingClips: 512 }); expect(fetchBinary).toHaveBeenCalledTimes(2);+ events.stopAll(); clip.resolve(new ArrayBuffer(4)); await new Promise(done => setTimeout(done, 0));+ expect(events.getStats()).toMatchObject({ active: 0, pendingClips: 0, stopped: 512 });+ expect(backend.play).not.toHaveBeenCalled(); expect(audio.getBufferStats().bufferCount).toBe(0);+ });++ it('uses real minigame streaming and rate controls without fetching PCM bytes', async () => {+ let ended: (() => void) | undefined, paused = true;+ const context = { src: '', loop: false, volume: 1, playbackRate: 1, startTime: 0, obeyMuteSwitch: true,+ get paused() { return paused; }, duration: 1, currentTime: 0,+ play() { paused = false; }, pause() { paused = true; }, stop() { paused = true; },+ destroy: vi.fn(), onEnded(callback: () => void) { ended = callback; }, onError() {},+ } satisfies MiniGameInnerAudioContext;+ const actual = new MiniGameAudioBackend({ createInnerAudioContext: () => context } as unknown as MiniGameGlobal);+ const { events, fetchBinary, audio } = fixture({ volume: [.4, .4], playbackRate: [1.25, 1.25], maxInstances: 1 }, actual);+ const emitter = (await events.load('steps.esaudioevent', { seed: 5 }))!, request = emitter.trigger();+ expect(await request.ready).toBe('playing'); expect(context.src).toBe('a.wav');+ expect(context.playbackRate).toBe(1.25); expect(context.volume).toBe(.4); expect(fetchBinary).not.toHaveBeenCalled();+ audio.suspend(); events.update(.1); expect(emitter.trigger().reason).toBe('event-limit');+ audio.resume(); expect(request.isPlaying).toBe(true);+ paused = true; ended?.(); expect(request.status).toBe('ended'); expect(events.getStats().active).toBe(0);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex dba1db288..211266a7e 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -30,6 +30,8 @@ export const NOTES_FLOOR = 'v0.65.0';export const NOTED = {'refactor(audio): expose shared playback ownership':{ internal: 'Provides canonical voice-state lookup, stop generations and complete cleanup for leased consumers without adding another global voice pool.' },+ 'feat(audio): manage sound event playback lifetimes':+ { note: 'Sound event playback owns pending and paused voices.' },'feat(audio): add deterministic sound event definitions':{ note: 'Sound event definitions share deterministic selection.' },'feat(editor): recognize sound event definitions':