@flare-engine/audio 0.4.11 → 0.4.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -110,6 +110,8 @@ export declare class Music {
110
110
  private currentSource;
111
111
  private currentGain;
112
112
  private currentName;
113
+ private fadingSource;
114
+ private fadingGain;
113
115
  /** Name of the currently playing track, or null. */
114
116
  get playing(): string | null;
115
117
  /** Connect to an AudioContext and output gain node. */
@@ -118,15 +120,17 @@ export declare class Music {
118
120
  register(name: string, buffer: AudioBufferLike): void;
119
121
  /** Play a track. Stops any currently playing track. Loops by default. */
120
122
  play(name: string, loop?: boolean): void;
121
- /** Stop the current track. */
123
+ /** Stop the current track and any track still fading out from a crossfade. */
122
124
  stop(): void;
123
125
  /**
124
126
  * Crossfade to another track over duration seconds.
125
127
  * Fades out current and fades in the new track simultaneously.
128
+ * A track still fading out from an earlier crossfade is stopped at once.
126
129
  */
127
130
  crossfadeTo(name: string, duration: number, loop?: boolean): void;
128
131
  private startTrack;
129
132
  private stopInternal;
133
+ private stopFading;
130
134
  }
131
135
  /** Options for playing a sound effect. */
132
136
  interface PlaySFXOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/audio-manager.ts","../src/channels.ts","../src/music.ts","../src/sfx-pool.ts","../src/synth.ts"],"mappings":";;;;UAKiB;WACN;;UAGM;WACN,MAAM;EACf,QAAQ,MAAM,2BAA2B;EACzC;;UAGe;EACf;EACA,eAAe,eAAe;EAC9B,wBAAwB,eAAe;;UAGxB;WACN;WACA;WACA;WACA;;;UAIM,sBAAsB;EACrC,cAAc,QAAQ,cAAc,uBAAuB;;UAG5C;EACf,QAAQ;EACR;;;;;WAKS;IAAiB;;EAC1B,QAAQ,MAAM,eAAe;EAC7B;EACA,MAAM;EACN,KAAK;EACL,WAAW,MAAM,2BAA2B;;;;;EAK5C,YAAY;;UAGG;WACN;WACA;WACA,aAAa;EACtB,cAAc;EACd,sBAAsB;;;;;EAKtB,cAAc,0BAA0B,gBAAgB,qBAAqB;EAC7E,UAAU;EACV,WAAW;EACX,SAAS;;;KAaC;;;;;qBAMC;UACH;;MAGJ,SAAS;;MAMT,WAAW;;MAKX;;EAKJ,KAAK,eAAe;;EAMd,WAAW;;EAOX,UAAU;;EAOV,SAAS;;;UC1HA;WACN;;EAET;;WAES,MAAM;;;KAIL;;;;;wBAMI,eAAe,KAAK,mBAAmB,IAAI,aAAa;;;;;qBCN3D;UACH;UACA;UACA;UACA;UACA;UACA;;MAGJ;;EAKJ,QAAQ,KAAK,kBAAkB,QAAQ;;EAMvC,SAAS,cAAc,QAAQ;;EAK/B,KAAK,cAAc;;EAanB;;;;;EAQA,YAAY,cAAc,kBAAkB;UA4BpC;UAgCA;;;UClHO;;EAEf;;EAEA;;EAEA;;EAEA;;;UAIe;;EAEf;;;;;;qBAaW;UACH;UACA;UACA;UACA;UACA;EAEI,YAAA;;EAMZ,QAAQ,KAAK,kBAAkB,QAAQ;;EAMvC,SAAS,cAAc,QAAQ;;EAK/B,WAAW;;EAKX,IAAI;;MAKA;;MAKA;;EAKJ,KAAK,cAAc,OAAO,iBAAiB;;EAoE3C;;KC7IU;UAEK;;EAEf;;EAEA;;EAEA;;EAEA;;UAGe;EACf,MAAM;;EAEN;;EAEA;;EAEA;;EAEA,WAAW;;EAEX;;EAEA;;;wBAMc,iBAAiB,kBAAkB;;;;;wBASnC,YAAY,OAAO,YAAY,oBAAoB,KAAK;;wBAkDxD,cAAc,QAAQ,eAAe,KAAK"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/audio-manager.ts","../src/channels.ts","../src/music.ts","../src/sfx-pool.ts","../src/synth.ts"],"mappings":";;;;UAKiB;WACN;;UAGM;WACN,MAAM;EACf,QAAQ,MAAM,2BAA2B;EACzC;;UAGe;EACf;EACA,eAAe,eAAe;EAC9B,wBAAwB,eAAe;;UAGxB;WACN;WACA;WACA;WACA;;;UAIM,sBAAs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8 @@ export declare class Music {
110
110
  private currentSource;
111
111
  private currentGain;
112
112
  private currentName;
113
+ private fadingSource;
114
+ private fadingGain;
113
115
  /** Name of the currently playing track, or null. */
114
116
  get playing(): string | null;
115
117
  /** Connect to an AudioContext and output gain node. */
@@ -118,15 +120,17 @@ export declare class Music {
118
120
  register(name: string, buffer: AudioBufferLike): void;
119
121
  /** Play a track. Stops any currently playing track. Loops by default. */
120
122
  play(name: string, loop?: boolean): void;
121
- /** Stop the current track. */
123
+ /** Stop the current track and any track still fading out from a crossfade. */
122
124
  stop(): void;
123
125
  /**
124
126
  * Crossfade to another track over duration seconds.
125
127
  * Fades out current and fades in the new track simultaneously.
128
+ * A track still fading out from an earlier crossfade is stopped at once.
126
129
  */
127
130
  crossfadeTo(name: string, duration: number, loop?: boolean): void;
128
131
  private startTrack;
129
132
  private stopInternal;
133
+ private stopFading;
130
134
  }
131
135
  /** Options for playing a sound effect. */
132
136
  interface PlaySFXOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/audio-manager.ts","../src/channels.ts","../src/music.ts","../src/sfx-pool.ts","../src/synth.ts"],"mappings":";;;;UAKiB;WACN;;UAGM;WACN,MAAM;EACf,QAAQ,MAAM,2BAA2B;EACzC;;UAGe;EACf;EACA,eAAe,eAAe;EAC9B,wBAAwB,eAAe;;UAGxB;WACN;WACA;WACA;WACA;;;UAIM,sBAAsB;EACrC,cAAc,QAAQ,cAAc,uBAAuB;;UAG5C;EACf,QAAQ;EACR;;;;;WAKS;IAAiB;;EAC1B,QAAQ,MAAM,eAAe;EAC7B;EACA,MAAM;EACN,KAAK;EACL,WAAW,MAAM,2BAA2B;;;;;EAK5C,YAAY;;UAGG;WACN;WACA;WACA,aAAa;EACtB,cAAc;EACd,sBAAsB;;;;;EAKtB,cAAc,0BAA0B,gBAAgB,qBAAqB;EAC7E,UAAU;EACV,WAAW;EACX,SAAS;;;KAaC;;;;;qBAMC;UACH;;MAGJ,SAAS;;MAMT,WAAW;;MAKX;;EAKJ,KAAK,eAAe;;EAMd,WAAW;;EAOX,UAAU;;EAOV,SAAS;;;UC1HA;WACN;;EAET;;WAES,MAAM;;;KAIL;;;;;wBAMI,eAAe,KAAK,mBAAmB,IAAI,aAAa;;;;;qBCN3D;UACH;UACA;UACA;UACA;UACA;UACA;;MAGJ;;EAKJ,QAAQ,KAAK,kBAAkB,QAAQ;;EAMvC,SAAS,cAAc,QAAQ;;EAK/B,KAAK,cAAc;;EAanB;;;;;EAQA,YAAY,cAAc,kBAAkB;UA4BpC;UAgCA;;;UClHO;;EAEf;;EAEA;;EAEA;;EAEA;;;UAIe;;EAEf;;;;;;qBAaW;UACH;UACA;UACA;UACA;UACA;EAEI,YAAA;;EAMZ,QAAQ,KAAK,kBAAkB,QAAQ;;EAMvC,SAAS,cAAc,QAAQ;;EAK/B,WAAW;;EAKX,IAAI;;MAKA;;MAKA;;EAKJ,KAAK,cAAc,OAAO,iBAAiB;;EAoE3C;;KC7IU;UAEK;;EAEf;;EAEA;;EAEA;;EAEA;;UAGe;EACf,MAAM;;EAEN;;EAEA;;EAEA;;EAEA,WAAW;;EAEX;;EAEA;;;wBAMc,iBAAiB,kBAAkB;;;;;wBASnC,YAAY,OAAO,YAAY,oBAAoB,KAAK;;wBAkDxD,cAAc,QAAQ,eAAe,KAAK"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/audio-manager.ts","../src/channels.ts","../src/music.ts","../src/sfx-pool.ts","../src/synth.ts"],"mappings":";;;;UAKiB;WACN;;UAGM;WACN,MAAM;EACf,QAAQ,MAAM,2BAA2B;EACzC;;UAGe;EACf;EACA,eAAe,eAAe;EAC9B,wBAAwB,eAAe;;UAGxB;WACN;WACA;WACA;WACA;;;UAIM,sBAAsB;EACrC,cAAc,QAAQ,cAAc,uBAAuB;;UAG5C;EACf,QAAQ;EACR;;;;;WAKS;IAAiB;;EAC1B,QAAQ,MAAM,eAAe;EAC7B;EACA,MAAM;EACN,KAAK;EACL,WAAW,MAAM,2BAA2B;;;;;EAK5C,YAAY;;UAGG;WACN;WACA;WACA,aAAa;EACtB,cAAc;EACd,sBAAsB;;;;;EAKtB,cAAc,0BAA0B,gBAAgB,qBAAqB;EAC7E,UAAU;EACV,WAAW;EACX,SAAS;;;KAaC;;;;;qBAMC;UACH;;MAGJ,SAAS;;MAMT,WAAW;;MAKX;;EAKJ,KAAK,eAAe;;EAMd,WAAW;;EAOX,UAAU;;EAOV,SAAS;;;UC1HA;WACN;;EAET;;WAES,MAAM;;;KAIL;;;;;wBAMI,eAAe,KAAK,mBAAmB,IAAI,aAAa;;;;;qBCN3D;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;MAGJ;;EAKJ,QAAQ,KAAK,kBAAkB,QAAQ;;EAMvC,SAAS,cAAc,QAAQ;;EAK/B,KAAK,cAAc;;EAanB;;;;;;EASA,YAAY,cAAc,kBAAkB;UA+BpC;UAoCA;UAiBA;;;UC7IO;;EAEf;;EAEA;;EAEA;;EAEA;;;UAIe;;EAEf;;;;;;qBAaW;UACH;UACA;UACA;UACA;UACA;EAEI,YAAA;;EAMZ,QAAQ,KAAK,kBAAkB,QAAQ;;EAMvC,SAAS,cAAc,QAAQ;;EAK/B,WAAW;;EAKX,IAAI;;MAKA;;MAKA;;EAKJ,KAAK,cAAc,OAAO,iBAAiB;;EAoE3C;;KC7IU;UAEK;;EAEf;;EAEA;;EAEA;;EAEA;;UAGe;EACf,MAAM;;EAEN;;EAEA;;EAEA;;EAEA,WAAW;;EAEX;;EAEA;;;wBAMc,iBAAiB,kBAAkB;;;;;wBASnC,YAAY,OAAO,YAAY,oBAAoB,KAAK;;wBAkDxD,cAAc,QAAQ,eAAe,KAAK"}
package/dist/index.js CHANGED
@@ -92,6 +92,8 @@ var Music = class {
92
92
  currentSource = null;
93
93
  currentGain = null;
94
94
  currentName = null;
95
+ fadingSource = null;
96
+ fadingGain = null;
95
97
  /** Name of the currently playing track, or null. */
96
98
  get playing() {
97
99
  return this.currentName;
@@ -115,13 +117,14 @@ var Music = class {
115
117
  g.gain.value = 1;
116
118
  });
117
119
  }
118
- /** Stop the current track. */
120
+ /** Stop the current track and any track still fading out from a crossfade. */
119
121
  stop() {
120
122
  this.stopInternal();
121
123
  }
122
124
  /**
123
125
  * Crossfade to another track over duration seconds.
124
126
  * Fades out current and fades in the new track simultaneously.
127
+ * A track still fading out from an earlier crossfade is stopped at once.
125
128
  */
126
129
  crossfadeTo(name, duration, loop = true) {
127
130
  if (!this.ctx || !this.output) return;
@@ -136,6 +139,9 @@ var Music = class {
136
139
  try {
137
140
  oldSource.stop(now + duration);
138
141
  } catch {}
142
+ this.stopFading();
143
+ this.fadingSource = oldSource;
144
+ this.fadingGain = oldGain;
139
145
  }
140
146
  this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {
141
147
  g.gain.setValueAtTime(0, now);
@@ -160,6 +166,10 @@ var Music = class {
160
166
  this.currentGain = null;
161
167
  this.currentName = null;
162
168
  }
169
+ if (this.fadingSource === source) {
170
+ this.fadingSource = null;
171
+ this.fadingGain = null;
172
+ }
163
173
  gain.disconnect();
164
174
  });
165
175
  }
@@ -171,6 +181,15 @@ var Music = class {
171
181
  this.currentSource = null;
172
182
  this.currentGain = null;
173
183
  this.currentName = null;
184
+ this.stopFading();
185
+ }
186
+ stopFading() {
187
+ if (this.fadingSource) try {
188
+ this.fadingSource.stop();
189
+ } catch {}
190
+ if (this.fadingGain) this.fadingGain.disconnect();
191
+ this.fadingSource = null;
192
+ this.fadingGain = null;
174
193
  }
175
194
  };
176
195
  // src/sfx-pool.ts
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/audio-manager.ts","../src/channels.ts","../src/music.ts","../src/sfx-pool.ts","../src/synth.ts"],"sourcesContent":["/**\n * Minimal interfaces for the Web Audio API subset we use.\n * At runtime these are provided by react-native-audio-api.\n */\n\nexport interface AudioDestinationNodeLike {\n readonly channelCount: number;\n}\n\nexport interface GainNodeLike {\n readonly gain: AudioParamLike;\n connect(dest: AudioDestinationNodeLike | GainNodeLike): void;\n disconnect(): void;\n}\n\nexport interface AudioParamLike {\n value: number;\n setValueAtTime(value: number, time: number): void;\n linearRampToValueAtTime(value: number, time: number): void;\n}\n\nexport interface AudioBufferLike {\n readonly duration: number;\n readonly numberOfChannels: number;\n readonly sampleRate: number;\n readonly length: number;\n}\n\n/** Writable `AudioBuffer` shape (`copyToChannel` exists on the DOM and in react-native-audio-api). */\nexport interface PCMBufferLike extends AudioBufferLike {\n copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;\n}\n\nexport interface AudioBufferSourceNodeLike {\n buffer: AudioBufferLike | null;\n loop: boolean;\n /**\n * Playback-rate param (Web Audio shape). Optional — not every injected node\n * exposes it; `SFXPool.play`'s `rate` option is a no-op when this is absent.\n */\n readonly playbackRate?: { value: number };\n connect(dest: GainNodeLike | AudioDestinationNodeLike): void;\n disconnect(): void;\n start(when?: number): void;\n stop(when?: number): void;\n onended: ((this: AudioBufferSourceNodeLike, ev: unknown) => void) | null;\n /**\n * End-of-playback callback as `react-native-audio-api` spells it; the DOM spells it\n * `onended`. A node exposes one or the other — register through `setSourceEndHandler`.\n */\n onEnded?: ((ev: unknown) => void) | null;\n}\n\nexport interface AudioContextLike {\n readonly state: 'suspended' | 'running' | 'closed';\n readonly currentTime: number;\n readonly destination: AudioDestinationNodeLike;\n createGain(): GainNodeLike;\n createBufferSource(): AudioBufferSourceNodeLike;\n /**\n * Allocates a writable buffer for `fillPCMBuffer`. Optional so hand-written contexts\n * keep type-checking.\n */\n createBuffer?(numberOfChannels: number, length: number, sampleRate: number): PCMBufferLike;\n resume(): Promise<void>;\n suspend(): Promise<void>;\n close(): Promise<void>;\n}\n\n/** Registers the end-of-playback handler on whichever accessor the node exposes. */\nexport function setSourceEndHandler(source: AudioBufferSourceNodeLike, handler: () => void): void {\n if ('onEnded' in source) {\n source.onEnded = handler;\n } else {\n source.onended = handler;\n }\n}\n\n/** Audio context state. */\nexport type AudioState = 'uninitialized' | 'running' | 'suspended' | 'closed';\n\n/**\n * AudioManager — manages the AudioContext lifecycle.\n * Wraps react-native-audio-api's AudioContext.\n */\nexport class AudioManager {\n private ctx: AudioContextLike | null = null;\n\n /** Current audio state. */\n get state(): AudioState {\n if (!this.ctx) return 'uninitialized';\n return this.ctx.state === 'closed' ? 'closed' : this.ctx.state;\n }\n\n /** The underlying AudioContext, or null if not initialized. */\n get context(): AudioContextLike | null {\n return this.ctx;\n }\n\n /** Current time from the AudioContext. */\n get currentTime(): number {\n return this.ctx?.currentTime ?? 0;\n }\n\n /** Initialize with a factory that creates the native AudioContext. */\n init(factory: () => AudioContextLike): void {\n if (this.ctx) return;\n this.ctx = factory();\n }\n\n /** Suspend audio. Call from your own background handler — no automatic wiring. */\n async suspend(): Promise<void> {\n if (this.ctx?.state === 'running') {\n await this.ctx.suspend();\n }\n }\n\n /** Resume audio. Call from your own foreground handler — no automatic wiring. */\n async resume(): Promise<void> {\n if (this.ctx?.state === 'suspended') {\n await this.ctx.resume();\n }\n }\n\n /** Close and dispose the AudioContext. */\n async close(): Promise<void> {\n if (this.ctx) {\n await this.ctx.close();\n this.ctx = null;\n }\n }\n}\n","import type { AudioContextLike, GainNodeLike } from './audio-manager.js';\n\n/** A volume channel that wraps a GainNode. */\nexport interface Channel {\n readonly name: string;\n /** Current volume (0.0 - 1.0). */\n volume: number;\n /** The underlying GainNode. */\n readonly node: GainNodeLike;\n}\n\n/** Standard channel names. */\nexport type ChannelName = 'master' | 'sfx' | 'music';\n\n/**\n * Creates volume channels connected: sfx → master, music → master, master → destination.\n * Returns a map of channels by name.\n */\nexport function createChannels(ctx: AudioContextLike): Map<ChannelName, Channel> {\n const masterGain = ctx.createGain();\n masterGain.gain.value = 1;\n masterGain.connect(ctx.destination);\n\n const sfxGain = ctx.createGain();\n sfxGain.gain.value = 1;\n sfxGain.connect(masterGain);\n\n const musicGain = ctx.createGain();\n musicGain.gain.value = 1;\n musicGain.connect(masterGain);\n\n const channels = new Map<ChannelName, Channel>();\n\n channels.set('master', createChannel('master', masterGain));\n channels.set('sfx', createChannel('sfx', sfxGain));\n channels.set('music', createChannel('music', musicGain));\n\n return channels;\n}\n\nfunction createChannel(name: string, node: GainNodeLike): Channel {\n let vol = 1;\n return {\n name,\n get volume() {\n return vol;\n },\n set volume(v: number) {\n vol = Math.max(0, Math.min(1, v));\n node.gain.value = vol;\n },\n node,\n };\n}\n","import type {\n AudioBufferLike,\n AudioBufferSourceNodeLike,\n AudioContextLike,\n GainNodeLike,\n} from './audio-manager.js';\nimport { setSourceEndHandler } from './audio-manager.js';\n\n/**\n * Music player — one track at a time, with crossfade support.\n * Loops by default.\n */\nexport class Music {\n private ctx: AudioContextLike | null = null;\n private output: GainNodeLike | null = null;\n private buffers = new Map<string, AudioBufferLike>();\n private currentSource: AudioBufferSourceNodeLike | null = null;\n private currentGain: GainNodeLike | null = null;\n private currentName: string | null = null;\n\n /** Name of the currently playing track, or null. */\n get playing(): string | null {\n return this.currentName;\n }\n\n /** Connect to an AudioContext and output gain node. */\n connect(ctx: AudioContextLike, output: GainNodeLike): void {\n this.ctx = ctx;\n this.output = output;\n }\n\n /** Register a music track buffer. */\n register(name: string, buffer: AudioBufferLike): void {\n this.buffers.set(name, buffer);\n }\n\n /** Play a track. Stops any currently playing track. Loops by default. */\n play(name: string, loop = true): void {\n if (!this.ctx || !this.output) return;\n const buffer = this.buffers.get(name);\n if (!buffer) return;\n\n this.stopInternal();\n\n this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {\n g.gain.value = 1;\n });\n }\n\n /** Stop the current track. */\n stop(): void {\n this.stopInternal();\n }\n\n /**\n * Crossfade to another track over duration seconds.\n * Fades out current and fades in the new track simultaneously.\n */\n crossfadeTo(name: string, duration: number, loop = true): void {\n if (!this.ctx || !this.output) return;\n const buffer = this.buffers.get(name);\n if (!buffer) return;\n\n const now = this.ctx.currentTime;\n\n // Fade out current\n if (this.currentGain && this.currentSource) {\n const oldGain = this.currentGain;\n const oldSource = this.currentSource;\n oldGain.gain.setValueAtTime(oldGain.gain.value, now);\n oldGain.gain.linearRampToValueAtTime(0, now + duration);\n // Schedule stop after fade\n try {\n oldSource.stop(now + duration);\n } catch {\n // Already stopped\n }\n }\n\n // Start new track fading in\n this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {\n g.gain.setValueAtTime(0, now);\n g.gain.linearRampToValueAtTime(1, now + duration);\n });\n }\n\n private startTrack(\n ctx: AudioContextLike,\n output: GainNodeLike,\n name: string,\n buffer: AudioBufferLike,\n loop: boolean,\n prime: (gain: GainNodeLike) => void,\n ): void {\n const source = ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = loop;\n\n const gain = ctx.createGain();\n prime(gain);\n source.connect(gain);\n gain.connect(output);\n\n source.start();\n this.currentSource = source;\n this.currentGain = gain;\n this.currentName = name;\n\n setSourceEndHandler(source, () => {\n if (this.currentSource === source) {\n this.currentSource = null;\n this.currentGain = null;\n this.currentName = null;\n }\n gain.disconnect();\n });\n }\n\n private stopInternal(): void {\n if (this.currentSource) {\n try {\n this.currentSource.stop();\n } catch {\n // Already stopped\n }\n }\n if (this.currentGain) {\n this.currentGain.disconnect();\n }\n this.currentSource = null;\n this.currentGain = null;\n this.currentName = null;\n }\n}\n","import type { AudioBufferLike, AudioContextLike, GainNodeLike } from './audio-manager.js';\nimport { setSourceEndHandler } from './audio-manager.js';\n\n/** Options for playing a sound effect. */\nexport interface PlaySFXOptions {\n /** Playback volume (0-1). Default: 1. */\n volume?: number;\n /** Playback rate multiplier. Default: 1. Applied only when the audio node exposes a `playbackRate` param. */\n rate?: number;\n /** Whether to loop. Default: false. */\n loop?: boolean;\n /** Seconds to wait before starting, on the context clock. Default: 0 (start at once). Non-finite or non-positive values start at once. */\n delay?: number;\n}\n\n/** A handle to a playing SFX instance. */\nexport interface SFXHandle {\n /** Stop playback. */\n stop(): void;\n}\n\n/** Tracks an active playing source. */\ninterface ActiveSource {\n name: string;\n stop(): void;\n}\n\n/**\n * SFX pool — pre-decoded audio buffers with polyphony management.\n * When max polyphony is reached, the oldest sound is killed.\n */\nexport class SFXPool {\n private buffers = new Map<string, AudioBufferLike>();\n private active: ActiveSource[] = [];\n private ctx: AudioContextLike | null = null;\n private output: GainNodeLike | null = null;\n private maxPolyphony: number;\n\n constructor(maxPolyphony = 16) {\n if (maxPolyphony <= 0) throw new Error('SFXPool: maxPolyphony must be > 0');\n this.maxPolyphony = maxPolyphony;\n }\n\n /** Connect to an AudioContext and output GainNode. */\n connect(ctx: AudioContextLike, output: GainNodeLike): void {\n this.ctx = ctx;\n this.output = output;\n }\n\n /** Register a pre-decoded audio buffer. */\n register(name: string, buffer: AudioBufferLike): void {\n this.buffers.set(name, buffer);\n }\n\n /** Unregister a buffer. */\n unregister(name: string): void {\n this.buffers.delete(name);\n }\n\n /** Check if a buffer is registered. */\n has(name: string): boolean {\n return this.buffers.has(name);\n }\n\n /** Number of registered buffers. */\n get size(): number {\n return this.buffers.size;\n }\n\n /** Number of currently active sounds. */\n get activeCount(): number {\n return this.active.length;\n }\n\n /** Play a registered sound. Returns a handle, or null if not registered/no context. */\n play(name: string, opts?: PlaySFXOptions): SFXHandle | null {\n const buffer = this.buffers.get(name);\n if (!buffer || !this.ctx || !this.output) return null;\n\n // Kill oldest if at max polyphony\n while (this.active.length >= this.maxPolyphony) {\n const oldest = this.active.shift();\n oldest?.stop();\n }\n\n const source = this.ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = opts?.loop ?? false;\n\n // Apply playback rate when the injected node exposes the param (Web Audio shape).\n const rateParam = source.playbackRate;\n if (rateParam && opts?.rate !== undefined) {\n rateParam.value = opts.rate;\n }\n\n // Create a per-source gain for volume control\n const gain = this.ctx.createGain();\n gain.gain.value = opts?.volume ?? 1;\n source.connect(gain);\n gain.connect(this.output);\n\n const entry: ActiveSource = {\n name,\n stop() {\n try {\n source.stop();\n } catch {\n // Already stopped\n }\n gain.disconnect();\n },\n };\n\n this.active.push(entry);\n\n // Clean up when playback ends\n setSourceEndHandler(source, () => {\n const idx = this.active.indexOf(entry);\n if (idx !== -1) {\n this.active.splice(idx, 1);\n }\n gain.disconnect();\n });\n\n const delay = opts?.delay;\n if (delay !== undefined && Number.isFinite(delay) && delay > 0) {\n source.start(this.ctx.currentTime + delay);\n } else {\n source.start();\n }\n\n return {\n stop: () => {\n entry.stop();\n const idx = this.active.indexOf(entry);\n if (idx !== -1) {\n this.active.splice(idx, 1);\n }\n },\n };\n }\n\n /** Stop all active sounds. */\n stopAll(): void {\n for (const entry of this.active) {\n entry.stop();\n }\n this.active.length = 0;\n }\n}\n","import type { PCMBufferLike } from './audio-manager.js';\n\nexport type SynthWaveform = 'sine' | 'square' | 'saw' | 'noise';\n\nexport interface SynthEnvelope {\n /** Seconds from silence to full level. */\n attack: number;\n /** Seconds from full level down to `sustain`. */\n decay: number;\n /** Level (0–1) held after the decay until the release starts. */\n sustain: number;\n /** Seconds of fade to silence, counted back from the end of the sound. */\n release: number;\n}\n\nexport interface SynthSound {\n wave: SynthWaveform;\n /** Hz at the start. Ignored by `noise`. */\n frequency: number;\n /** Hz at the end, reached by a linear sweep from `frequency`. Default: `frequency` (no sweep). */\n endFrequency?: number;\n /** Seconds. */\n duration: number;\n /** Default: `{ attack: 0, decay: 0, sustain: 1, release: 0 }` (flat). */\n envelope?: SynthEnvelope;\n /** Peak amplitude (0–1). Default 1. */\n volume?: number;\n /** 32-bit seed for `noise`; the same seed renders the same samples. Default 1. */\n seed?: number;\n}\n\nconst TWO_PI = Math.PI * 2;\n\n/** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */\nexport function synthSampleCount(duration: number, sampleRate: number): number {\n if (!Number.isFinite(duration) || duration < 0) return 0;\n return Math.ceil(duration * sampleRate);\n}\n\n/**\n * Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples\n * written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.\n */\nexport function renderSynth(sound: SynthSound, sampleRate: number, out: Float32Array): number {\n if (!Number.isFinite(sampleRate) || sampleRate <= 0) return 0;\n const duration = sound.duration;\n const n = Math.min(out.length, synthSampleCount(duration, sampleRate));\n const wave = sound.wave;\n const volume = sound.volume ?? 1;\n const f0 = sound.frequency;\n const sweep = ((sound.endFrequency ?? f0) - f0) / duration;\n const env = sound.envelope;\n const attack = env ? env.attack : 0;\n const decay = env ? env.decay : 0;\n const sustain = env ? env.sustain : 1;\n const release = env ? env.release : 0;\n const decayEnd = attack + decay;\n const releaseStart = duration - release;\n const dt = 1 / sampleRate;\n let phase = 0;\n let rng = (sound.seed ?? 1) | 0 || 1;\n\n for (let i = 0; i < n; i++) {\n const t = i * dt;\n let osc: number;\n switch (wave) {\n case 'sine':\n osc = Math.sin(TWO_PI * phase);\n break;\n case 'square':\n osc = phase < 0.5 ? 1 : -1;\n break;\n case 'saw':\n osc = 2 * phase - 1;\n break;\n default:\n rng ^= rng << 13;\n rng ^= rng >>> 17;\n rng ^= rng << 5;\n osc = (rng >>> 0) / 2147483648 - 1;\n break;\n }\n let gain =\n t < attack ? t / attack : t < decayEnd ? 1 - ((1 - sustain) * (t - attack)) / decay : sustain;\n if (release > 0 && t >= releaseStart) gain *= (duration - t) / release;\n out[i] = osc * gain * volume;\n phase += (f0 + sweep * t) * dt;\n if (phase >= 1) phase -= Math.floor(phase);\n }\n return n;\n}\n\n/** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */\nexport function fillPCMBuffer(buffer: PCMBufferLike, pcm: Float32Array): void {\n for (let c = 0; c < buffer.numberOfChannels; c++) buffer.copyToChannel(pcm, c);\n}\n"],"mappings":";;;AAsEA,SAAgB,oBAAoB,QAAmC,SAA2B;CAChG,IAAI,aAAa,QACf,OAAO,UAAU;MAEjB,OAAO,UAAU;AAErB;;;;;AASA,IAAa,eAAb,MAA0B;CACxB,MAAuC;;CAGvC,IAAI,QAAoB;EACtB,IAAI,CAAC,KAAK,KAAK,OAAO;E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,KAAK,cAAc,SAAS,WAAW,KAAK;EAC/D,IAAI,KAAK,MAAM,OAAO;EACtB,UAAU,KAAK,QAAQ,KAAK;EAC5B,IAAI,SAAS,GAAG,SAAS,KAAK,MAAM,KAAK;CAC3C;CACA,OAAO;AACT;;AAGA,SAAgB,cAAc,QAAuB,KAAyB;CAC5E,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,kBAAkB,KAAK,OAAO,cAAc,KAAK,CAAC;AAC/E"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/audio-manager.ts","../src/channels.ts","../src/music.ts","../src/sfx-pool.ts","../src/synth.ts"],"sourcesContent":["/**\n * Minimal interfaces for the Web Audio API subset we use.\n * At runtime these are provided by react-native-audio-api.\n */\n\nexport interface AudioDestinationNodeLike {\n readonly channelCount: number;\n}\n\nexport interface GainNodeLike {\n readonly gain: AudioParamLike;\n connect(dest: AudioDestinationNodeLike | GainNodeLike): void;\n disconnect(): void;\n}\n\nexport interface AudioParamLike {\n value: number;\n setValueAtTime(value: number, time: number): void;\n linearRampToValueAtTime(value: number, time: number): void;\n}\n\nexport interface AudioBufferLike {\n readonly duration: number;\n readonly numberOfChannels: number;\n readonly sampleRate: number;\n readonly length: number;\n}\n\n/** Writable `AudioBuffer` shape (`copyToChannel` exists on the DOM and in react-native-audio-api). */\nexport interface PCMBufferLike extends AudioBufferLike {\n copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;\n}\n\nexport interface AudioBufferSourceNodeLike {\n buffer: AudioBufferLike | null;\n loop: boolean;\n /**\n * Playback-rate param (Web Audio shape). Optional — not every injected node\n * exposes it; `SFXPool.play`'s `rate` option is a no-op when this is absent.\n */\n readonly playbackRate?: { value: number };\n connect(dest: GainNodeLike | AudioDestinationNodeLike): void;\n disconnect(): void;\n start(when?: number): void;\n stop(when?: number): void;\n onended: ((this: AudioBufferSourceNodeLike, ev: unknown) => void) | null;\n /**\n * End-of-playback callback as `react-native-audio-api` spells it; the DOM spells it\n * `onended`. A node exposes one or the other — register through `setSourceEndHandler`.\n */\n onEnded?: ((ev: unknown) => void) | null;\n}\n\nexport interface AudioContextLike {\n readonly state: 'suspended' | 'running' | 'closed';\n readonly currentTime: number;\n readonly destination: AudioDestinationNodeLike;\n createGain(): GainNodeLike;\n createBufferSource(): AudioBufferSourceNodeLike;\n /**\n * Allocates a writable buffer for `fillPCMBuffer`. Optional so hand-written contexts\n * keep type-checking.\n */\n createBuffer?(numberOfChannels: number, length: number, sampleRate: number): PCMBufferLike;\n resume(): Promise<void>;\n suspend(): Promise<void>;\n close(): Promise<void>;\n}\n\n/** Registers the end-of-playback handler on whichever accessor the node exposes. */\nexport function setSourceEndHandler(source: AudioBufferSourceNodeLike, handler: () => void): void {\n if ('onEnded' in source) {\n source.onEnded = handler;\n } else {\n source.onended = handler;\n }\n}\n\n/** Audio context state. */\nexport type AudioState = 'uninitialized' | 'running' | 'suspended' | 'closed';\n\n/**\n * AudioManager — manages the AudioContext lifecycle.\n * Wraps react-native-audio-api's AudioContext.\n */\nexport class AudioManager {\n private ctx: AudioContextLike | null = null;\n\n /** Current audio state. */\n get state(): AudioState {\n if (!this.ctx) return 'uninitialized';\n return this.ctx.state === 'closed' ? 'closed' : this.ctx.state;\n }\n\n /** The underlying AudioContext, or null if not initialized. */\n get context(): AudioContextLike | null {\n return this.ctx;\n }\n\n /** Current time from the AudioContext. */\n get currentTime(): number {\n return this.ctx?.currentTime ?? 0;\n }\n\n /** Initialize with a factory that creates the native AudioContext. */\n init(factory: () => AudioContextLike): void {\n if (this.ctx) return;\n this.ctx = factory();\n }\n\n /** Suspend audio. Call from your own background handler — no automatic wiring. */\n async suspend(): Promise<void> {\n if (this.ctx?.state === 'running') {\n await this.ctx.suspend();\n }\n }\n\n /** Resume audio. Call from your own foreground handler — no automatic wiring. */\n async resume(): Promise<void> {\n if (this.ctx?.state === 'suspended') {\n await this.ctx.resume();\n }\n }\n\n /** Close and dispose the AudioContext. */\n async close(): Promise<void> {\n if (this.ctx) {\n await this.ctx.close();\n this.ctx = null;\n }\n }\n}\n","import type { AudioContextLike, GainNodeLike } from './audio-manager.js';\n\n/** A volume channel that wraps a GainNode. */\nexport interface Channel {\n readonly name: string;\n /** Current volume (0.0 - 1.0). */\n volume: number;\n /** The underlying GainNode. */\n readonly node: GainNodeLike;\n}\n\n/** Standard channel names. */\nexport type ChannelName = 'master' | 'sfx' | 'music';\n\n/**\n * Creates volume channels connected: sfx → master, music → master, master → destination.\n * Returns a map of channels by name.\n */\nexport function createChannels(ctx: AudioContextLike): Map<ChannelName, Channel> {\n const masterGain = ctx.createGain();\n masterGain.gain.value = 1;\n masterGain.connect(ctx.destination);\n\n const sfxGain = ctx.createGain();\n sfxGain.gain.value = 1;\n sfxGain.connect(masterGain);\n\n const musicGain = ctx.createGain();\n musicGain.gain.value = 1;\n musicGain.connect(masterGain);\n\n const channels = new Map<ChannelName, Channel>();\n\n channels.set('master', createChannel('master', masterGain));\n channels.set('sfx', createChannel('sfx', sfxGain));\n channels.set('music', createChannel('music', musicGain));\n\n return channels;\n}\n\nfunction createChannel(name: string, node: GainNodeLike): Channel {\n let vol = 1;\n return {\n name,\n get volume() {\n return vol;\n },\n set volume(v: number) {\n vol = Math.max(0, Math.min(1, v));\n node.gain.value = vol;\n },\n node,\n };\n}\n","import type {\n AudioBufferLike,\n AudioBufferSourceNodeLike,\n AudioContextLike,\n GainNodeLike,\n} from './audio-manager.js';\nimport { setSourceEndHandler } from './audio-manager.js';\n\n/**\n * Music player — one track at a time, with crossfade support.\n * Loops by default.\n */\nexport class Music {\n private ctx: AudioContextLike | null = null;\n private output: GainNodeLike | null = null;\n private buffers = new Map<string, AudioBufferLike>();\n private currentSource: AudioBufferSourceNodeLike | null = null;\n private currentGain: GainNodeLike | null = null;\n private currentName: string | null = null;\n private fadingSource: AudioBufferSourceNodeLike | null = null;\n private fadingGain: GainNodeLike | null = null;\n\n /** Name of the currently playing track, or null. */\n get playing(): string | null {\n return this.currentName;\n }\n\n /** Connect to an AudioContext and output gain node. */\n connect(ctx: AudioContextLike, output: GainNodeLike): void {\n this.ctx = ctx;\n this.output = output;\n }\n\n /** Register a music track buffer. */\n register(name: string, buffer: AudioBufferLike): void {\n this.buffers.set(name, buffer);\n }\n\n /** Play a track. Stops any currently playing track. Loops by default. */\n play(name: string, loop = true): void {\n if (!this.ctx || !this.output) return;\n const buffer = this.buffers.get(name);\n if (!buffer) return;\n\n this.stopInternal();\n\n this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {\n g.gain.value = 1;\n });\n }\n\n /** Stop the current track and any track still fading out from a crossfade. */\n stop(): void {\n this.stopInternal();\n }\n\n /**\n * Crossfade to another track over duration seconds.\n * Fades out current and fades in the new track simultaneously.\n * A track still fading out from an earlier crossfade is stopped at once.\n */\n crossfadeTo(name: string, duration: number, loop = true): void {\n if (!this.ctx || !this.output) return;\n const buffer = this.buffers.get(name);\n if (!buffer) return;\n\n const now = this.ctx.currentTime;\n\n // Fade out current\n if (this.currentGain && this.currentSource) {\n const oldGain = this.currentGain;\n const oldSource = this.currentSource;\n oldGain.gain.setValueAtTime(oldGain.gain.value, now);\n oldGain.gain.linearRampToValueAtTime(0, now + duration);\n // Schedule stop after fade\n try {\n oldSource.stop(now + duration);\n } catch {\n // Already stopped\n }\n this.stopFading();\n this.fadingSource = oldSource;\n this.fadingGain = oldGain;\n }\n\n // Start new track fading in\n this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {\n g.gain.setValueAtTime(0, now);\n g.gain.linearRampToValueAtTime(1, now + duration);\n });\n }\n\n private startTrack(\n ctx: AudioContextLike,\n output: GainNodeLike,\n name: string,\n buffer: AudioBufferLike,\n loop: boolean,\n prime: (gain: GainNodeLike) => void,\n ): void {\n const source = ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = loop;\n\n const gain = ctx.createGain();\n prime(gain);\n source.connect(gain);\n gain.connect(output);\n\n source.start();\n this.currentSource = source;\n this.currentGain = gain;\n this.currentName = name;\n\n setSourceEndHandler(source, () => {\n if (this.currentSource === source) {\n this.currentSource = null;\n this.currentGain = null;\n this.currentName = null;\n }\n if (this.fadingSource === source) {\n this.fadingSource = null;\n this.fadingGain = null;\n }\n gain.disconnect();\n });\n }\n\n private stopInternal(): void {\n if (this.currentSource) {\n try {\n this.currentSource.stop();\n } catch {\n // Already stopped\n }\n }\n if (this.currentGain) {\n this.currentGain.disconnect();\n }\n this.currentSource = null;\n this.currentGain = null;\n this.currentName = null;\n this.stopFading();\n }\n\n private stopFading(): void {\n if (this.fadingSource) {\n try {\n this.fadingSource.stop();\n } catch {\n // Already stopped\n }\n }\n if (this.fadingGain) {\n this.fadingGain.disconnect();\n }\n this.fadingSource = null;\n this.fadingGain = null;\n }\n}\n","import type { AudioBufferLike, AudioContextLike, GainNodeLike } from './audio-manager.js';\nimport { setSourceEndHandler } from './audio-manager.js';\n\n/** Options for playing a sound effect. */\nexport interface PlaySFXOptions {\n /** Playback volume (0-1). Default: 1. */\n volume?: number;\n /** Playback rate multiplier. Default: 1. Applied only when the audio node exposes a `playbackRate` param. */\n rate?: number;\n /** Whether to loop. Default: false. */\n loop?: boolean;\n /** Seconds to wait before starting, on the context clock. Default: 0 (start at once). Non-finite or non-positive values start at once. */\n delay?: number;\n}\n\n/** A handle to a playing SFX instance. */\nexport interface SFXHandle {\n /** Stop playback. */\n stop(): void;\n}\n\n/** Tracks an active playing source. */\ninterface ActiveSource {\n name: string;\n stop(): void;\n}\n\n/**\n * SFX pool — pre-decoded audio buffers with polyphony management.\n * When max polyphony is reached, the oldest sound is killed.\n */\nexport class SFXPool {\n private buffers = new Map<string, AudioBufferLike>();\n private active: ActiveSource[] = [];\n private ctx: AudioContextLike | null = null;\n private output: GainNodeLike | null = null;\n private maxPolyphony: number;\n\n constructor(maxPolyphony = 16) {\n if (maxPolyphony <= 0) throw new Error('SFXPool: maxPolyphony must be > 0');\n this.maxPolyphony = maxPolyphony;\n }\n\n /** Connect to an AudioContext and output GainNode. */\n connect(ctx: AudioContextLike, output: GainNodeLike): void {\n this.ctx = ctx;\n this.output = output;\n }\n\n /** Register a pre-decoded audio buffer. */\n register(name: string, buffer: AudioBufferLike): void {\n this.buffers.set(name, buffer);\n }\n\n /** Unregister a buffer. */\n unregister(name: string): void {\n this.buffers.delete(name);\n }\n\n /** Check if a buffer is registered. */\n has(name: string): boolean {\n return this.buffers.has(name);\n }\n\n /** Number of registered buffers. */\n get size(): number {\n return this.buffers.size;\n }\n\n /** Number of currently active sounds. */\n get activeCount(): number {\n return this.active.length;\n }\n\n /** Play a registered sound. Returns a handle, or null if not registered/no context. */\n play(name: string, opts?: PlaySFXOptions): SFXHandle | null {\n const buffer = this.buffers.get(name);\n if (!buffer || !this.ctx || !this.output) return null;\n\n // Kill oldest if at max polyphony\n while (this.active.length >= this.maxPolyphony) {\n const oldest = this.active.shift();\n oldest?.stop();\n }\n\n const source = this.ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = opts?.loop ?? false;\n\n // Apply playback rate when the injected node exposes the param (Web Audio shape).\n const rateParam = source.playbackRate;\n if (rateParam && opts?.rate !== undefined) {\n rateParam.value = opts.rate;\n }\n\n // Create a per-source gain for volume control\n const gain = this.ctx.createGain();\n gain.gain.value = opts?.volume ?? 1;\n source.connect(gain);\n gain.connect(this.output);\n\n const entry: ActiveSource = {\n name,\n stop() {\n try {\n source.stop();\n } catch {\n // Already stopped\n }\n gain.disconnect();\n },\n };\n\n this.active.push(entry);\n\n // Clean up when playback ends\n setSourceEndHandler(source, () => {\n const idx = this.active.indexOf(entry);\n if (idx !== -1) {\n this.active.splice(idx, 1);\n }\n gain.disconnect();\n });\n\n const delay = opts?.delay;\n if (delay !== undefined && Number.isFinite(delay) && delay > 0) {\n source.start(this.ctx.currentTime + delay);\n } else {\n source.start();\n }\n\n return {\n stop: () => {\n entry.stop();\n const idx = this.active.indexOf(entry);\n if (idx !== -1) {\n this.active.splice(idx, 1);\n }\n },\n };\n }\n\n /** Stop all active sounds. */\n stopAll(): void {\n for (const entry of this.active) {\n entry.stop();\n }\n this.active.length = 0;\n }\n}\n","import type { PCMBufferLike } from './audio-manager.js';\n\nexport type SynthWaveform = 'sine' | 'square' | 'saw' | 'noise';\n\nexport interface SynthEnvelope {\n /** Seconds from silence to full level. */\n attack: number;\n /** Seconds from full level down to `sustain`. */\n decay: number;\n /** Level (0–1) held after the decay until the release starts. */\n sustain: number;\n /** Seconds of fade to silence, counted back from the end of the sound. */\n release: number;\n}\n\nexport interface SynthSound {\n wave: SynthWaveform;\n /** Hz at the start. Ignored by `noise`. */\n frequency: number;\n /** Hz at the end, reached by a linear sweep from `frequency`. Default: `frequency` (no sweep). */\n endFrequency?: number;\n /** Seconds. */\n duration: number;\n /** Default: `{ attack: 0, decay: 0, sustain: 1, release: 0 }` (flat). */\n envelope?: SynthEnvelope;\n /** Peak amplitude (0–1). Default 1. */\n volume?: number;\n /** 32-bit seed for `noise`; the same seed renders the same samples. Default 1. */\n seed?: number;\n}\n\nconst TWO_PI = Math.PI * 2;\n\n/** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */\nexport function synthSampleCount(duration: number, sampleRate: number): number {\n if (!Number.isFinite(duration) || duration < 0) return 0;\n return Math.ceil(duration * sampleRate);\n}\n\n/**\n * Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples\n * written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.\n */\nexport function renderSynth(sound: SynthSound, sampleRate: number, out: Float32Array): number {\n if (!Number.isFinite(sampleRate) || sampleRate <= 0) return 0;\n const duration = sound.duration;\n const n = Math.min(out.length, synthSampleCount(duration, sampleRate));\n const wave = sound.wave;\n const volume = sound.volume ?? 1;\n const f0 = sound.frequency;\n const sweep = ((sound.endFrequency ?? f0) - f0) / duration;\n const env = sound.envelope;\n const attack = env ? env.attack : 0;\n const decay = env ? env.decay : 0;\n const sustain = env ? env.sustain : 1;\n const release = env ? env.release : 0;\n const decayEnd = attack + decay;\n const releaseStart = duration - release;\n const dt = 1 / sampleRate;\n let phase = 0;\n let rng = (sound.seed ?? 1) | 0 || 1;\n\n for (let i = 0; i < n; i++) {\n const t = i * dt;\n let osc: number;\n switch (wave) {\n case 'sine':\n osc = Math.sin(TWO_PI * phase);\n break;\n case 'square':\n osc = phase < 0.5 ? 1 : -1;\n break;\n case 'saw':\n osc = 2 * phase - 1;\n break;\n default:\n rng ^= rng << 13;\n rng ^= rng >>> 17;\n rng ^= rng << 5;\n osc = (rng >>> 0) / 2147483648 - 1;\n break;\n }\n let gain =\n t < attack ? t / attack : t < decayEnd ? 1 - ((1 - sustain) * (t - attack)) / decay : sustain;\n if (release > 0 && t >= releaseStart) gain *= (duration - t) / release;\n out[i] = osc * gain * volume;\n phase += (f0 + sweep * t) * dt;\n if (phase >= 1) phase -= Math.floor(phase);\n }\n return n;\n}\n\n/** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */\nexport function fillPCMBuffer(buffer: PCMBufferLike, pcm: Float32Array): void {\n for (let c = 0; c < buffer.numberOfChannels; c++) buffer.copyToChannel(pcm, c);\n}\n"],"mappings":";;;AAsEA,SAAgB,oBAAoB,QAAmC,SAA2B;CAChG,IAAI,aAAa,QACf,OAAO,UAAU;MAEjB,OAAO,UAAU;AAErB;;;;;AASA,IAAa,eAAb,MAA0B;CACxB,MAAuC;;CAGvC,IAAI,QAAoB;EACtB,IAAI,CAAC,KAAK,KAAK,OAAO;EACtB,OAAO,KAAK,IAAI,UAAU,WAAW,WAAW,KAAK,IAAI;CAC3D;;CAGA,IAAI,UAAmC;EACrC,OAAO,KAAK;CACd;;CAGA,IAAI,cAAsB;EACxB,OAAO,KAAK,KAAK,eAAe;CAClC;;CAGA,KAAK,SAAuC;EAC1C,IAAI,KAAK,KAAK;EACd,KAAK,MAAM,QAAQ;CACrB;;CAGA,MAAM,UAAyB;EAC7B,IAAI,KAAK,KAAK,UAAU,WACtB,MAAM,KAAK,IAAI,QAAQ;CAE3B;;CAGA,MAAM,SAAwB;EAC5B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,SAAS,WAAW,KAAK;EAC/D,IAAI,KAAK,MAAM,OAAO;EACtB,UAAU,KAAK,QAAQ,KAAK;EAC5B,IAAI,SAAS,GAAG,SAAS,KAAK,MAAM,KAAK;CAC3C;CACA,OAAO;AACT;;AAGA,SAAgB,cAAc,QAAuB,KAAyB;CAC5E,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,kBAAkB,KAAK,OAAO,cAAc,KAAK,CAAC;AAC/E"}
package/dist/index.mjs CHANGED
@@ -91,6 +91,8 @@ var Music = class {
91
91
  currentSource = null;
92
92
  currentGain = null;
93
93
  currentName = null;
94
+ fadingSource = null;
95
+ fadingGain = null;
94
96
  /** Name of the currently playing track, or null. */
95
97
  get playing() {
96
98
  return this.currentName;
@@ -114,13 +116,14 @@ var Music = class {
114
116
  g.gain.value = 1;
115
117
  });
116
118
  }
117
- /** Stop the current track. */
119
+ /** Stop the current track and any track still fading out from a crossfade. */
118
120
  stop() {
119
121
  this.stopInternal();
120
122
  }
121
123
  /**
122
124
  * Crossfade to another track over duration seconds.
123
125
  * Fades out current and fades in the new track simultaneously.
126
+ * A track still fading out from an earlier crossfade is stopped at once.
124
127
  */
125
128
  crossfadeTo(name, duration, loop = true) {
126
129
  if (!this.ctx || !this.output) return;
@@ -135,6 +138,9 @@ var Music = class {
135
138
  try {
136
139
  oldSource.stop(now + duration);
137
140
  } catch {}
141
+ this.stopFading();
142
+ this.fadingSource = oldSource;
143
+ this.fadingGain = oldGain;
138
144
  }
139
145
  this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {
140
146
  g.gain.setValueAtTime(0, now);
@@ -159,6 +165,10 @@ var Music = class {
159
165
  this.currentGain = null;
160
166
  this.currentName = null;
161
167
  }
168
+ if (this.fadingSource === source) {
169
+ this.fadingSource = null;
170
+ this.fadingGain = null;
171
+ }
162
172
  gain.disconnect();
163
173
  });
164
174
  }
@@ -170,6 +180,15 @@ var Music = class {
170
180
  this.currentSource = null;
171
181
  this.currentGain = null;
172
182
  this.currentName = null;
183
+ this.stopFading();
184
+ }
185
+ stopFading() {
186
+ if (this.fadingSource) try {
187
+ this.fadingSource.stop();
188
+ } catch {}
189
+ if (this.fadingGain) this.fadingGain.disconnect();
190
+ this.fadingSource = null;
191
+ this.fadingGain = null;
173
192
  }
174
193
  };
175
194
  // src/sfx-pool.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/audio-manager.ts","../src/channels.ts","../src/music.ts","../src/sfx-pool.ts","../src/synth.ts"],"sourcesContent":["/**\n * Minimal interfaces for the Web Audio API subset we use.\n * At runtime these are provided by react-native-audio-api.\n */\n\nexport interface AudioDestinationNodeLike {\n readonly channelCount: number;\n}\n\nexport interface GainNodeLike {\n readonly gain: AudioParamLike;\n connect(dest: AudioDestinationNodeLike | GainNodeLike): void;\n disconnect(): void;\n}\n\nexport interface AudioParamLike {\n value: number;\n setValueAtTime(value: number, time: number): void;\n linearRampToValueAtTime(value: number, time: number): void;\n}\n\nexport interface AudioBufferLike {\n readonly duration: number;\n readonly numberOfChannels: number;\n readonly sampleRate: number;\n readonly length: number;\n}\n\n/** Writable `AudioBuffer` shape (`copyToChannel` exists on the DOM and in react-native-audio-api). */\nexport interface PCMBufferLike extends AudioBufferLike {\n copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;\n}\n\nexport interface AudioBufferSourceNodeLike {\n buffer: AudioBufferLike | null;\n loop: boolean;\n /**\n * Playback-rate param (Web Audio shape). Optional — not every injected node\n * exposes it; `SFXPool.play`'s `rate` option is a no-op when this is absent.\n */\n readonly playbackRate?: { value: number };\n connect(dest: GainNodeLike | AudioDestinationNodeLike): void;\n disconnect(): void;\n start(when?: number): void;\n stop(when?: number): void;\n onended: ((this: AudioBufferSourceNodeLike, ev: unknown) => void) | null;\n /**\n * End-of-playback callback as `react-native-audio-api` spells it; the DOM spells it\n * `onended`. A node exposes one or the other — register through `setSourceEndHandler`.\n */\n onEnded?: ((ev: unknown) => void) | null;\n}\n\nexport interface AudioContextLike {\n readonly state: 'suspended' | 'running' | 'closed';\n readonly currentTime: number;\n readonly destination: AudioDestinationNodeLike;\n createGain(): GainNodeLike;\n createBufferSource(): AudioBufferSourceNodeLike;\n /**\n * Allocates a writable buffer for `fillPCMBuffer`. Optional so hand-written contexts\n * keep type-checking.\n */\n createBuffer?(numberOfChannels: number, length: number, sampleRate: number): PCMBufferLike;\n resume(): Promise<void>;\n suspend(): Promise<void>;\n close(): Promise<void>;\n}\n\n/** Registers the end-of-playback handler on whichever accessor the node exposes. */\nexport function setSourceEndHandler(source: AudioBufferSourceNodeLike, handler: () => void): void {\n if ('onEnded' in source) {\n source.onEnded = handler;\n } else {\n source.onended = handler;\n }\n}\n\n/** Audio context state. */\nexport type AudioState = 'uninitialized' | 'running' | 'suspended' | 'closed';\n\n/**\n * AudioManager — manages the AudioContext lifecycle.\n * Wraps react-native-audio-api's AudioContext.\n */\nexport class AudioManager {\n private ctx: AudioContextLike | null = null;\n\n /** Current audio state. */\n get state(): AudioState {\n if (!this.ctx) return 'uninitialized';\n return this.ctx.state === 'closed' ? 'closed' : this.ctx.state;\n }\n\n /** The underlying AudioContext, or null if not initialized. */\n get context(): AudioContextLike | null {\n return this.ctx;\n }\n\n /** Current time from the AudioContext. */\n get currentTime(): number {\n return this.ctx?.currentTime ?? 0;\n }\n\n /** Initialize with a factory that creates the native AudioContext. */\n init(factory: () => AudioContextLike): void {\n if (this.ctx) return;\n this.ctx = factory();\n }\n\n /** Suspend audio. Call from your own background handler — no automatic wiring. */\n async suspend(): Promise<void> {\n if (this.ctx?.state === 'running') {\n await this.ctx.suspend();\n }\n }\n\n /** Resume audio. Call from your own foreground handler — no automatic wiring. */\n async resume(): Promise<void> {\n if (this.ctx?.state === 'suspended') {\n await this.ctx.resume();\n }\n }\n\n /** Close and dispose the AudioContext. */\n async close(): Promise<void> {\n if (this.ctx) {\n await this.ctx.close();\n this.ctx = null;\n }\n }\n}\n","import type { AudioContextLike, GainNodeLike } from './audio-manager.js';\n\n/** A volume channel that wraps a GainNode. */\nexport interface Channel {\n readonly name: string;\n /** Current volume (0.0 - 1.0). */\n volume: number;\n /** The underlying GainNode. */\n readonly node: GainNodeLike;\n}\n\n/** Standard channel names. */\nexport type ChannelName = 'master' | 'sfx' | 'music';\n\n/**\n * Creates volume channels connected: sfx → master, music → master, master → destination.\n * Returns a map of channels by name.\n */\nexport function createChannels(ctx: AudioContextLike): Map<ChannelName, Channel> {\n const masterGain = ctx.createGain();\n masterGain.gain.value = 1;\n masterGain.connect(ctx.destination);\n\n const sfxGain = ctx.createGain();\n sfxGain.gain.value = 1;\n sfxGain.connect(masterGain);\n\n const musicGain = ctx.createGain();\n musicGain.gain.value = 1;\n musicGain.connect(masterGain);\n\n const channels = new Map<ChannelName, Channel>();\n\n channels.set('master', createChannel('master', masterGain));\n channels.set('sfx', createChannel('sfx', sfxGain));\n channels.set('music', createChannel('music', musicGain));\n\n return channels;\n}\n\nfunction createChannel(name: string, node: GainNodeLike): Channel {\n let vol = 1;\n return {\n name,\n get volume() {\n return vol;\n },\n set volume(v: number) {\n vol = Math.max(0, Math.min(1, v));\n node.gain.value = vol;\n },\n node,\n };\n}\n","import type {\n AudioBufferLike,\n AudioBufferSourceNodeLike,\n AudioContextLike,\n GainNodeLike,\n} from './audio-manager.js';\nimport { setSourceEndHandler } from './audio-manager.js';\n\n/**\n * Music player — one track at a time, with crossfade support.\n * Loops by default.\n */\nexport class Music {\n private ctx: AudioContextLike | null = null;\n private output: GainNodeLike | null = null;\n private buffers = new Map<string, AudioBufferLike>();\n private currentSource: AudioBufferSourceNodeLike | null = null;\n private currentGain: GainNodeLike | null = null;\n private currentName: string | null = null;\n\n /** Name of the currently playing track, or null. */\n get playing(): string | null {\n return this.currentName;\n }\n\n /** Connect to an AudioContext and output gain node. */\n connect(ctx: AudioContextLike, output: GainNodeLike): void {\n this.ctx = ctx;\n this.output = output;\n }\n\n /** Register a music track buffer. */\n register(name: string, buffer: AudioBufferLike): void {\n this.buffers.set(name, buffer);\n }\n\n /** Play a track. Stops any currently playing track. Loops by default. */\n play(name: string, loop = true): void {\n if (!this.ctx || !this.output) return;\n const buffer = this.buffers.get(name);\n if (!buffer) return;\n\n this.stopInternal();\n\n this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {\n g.gain.value = 1;\n });\n }\n\n /** Stop the current track. */\n stop(): void {\n this.stopInternal();\n }\n\n /**\n * Crossfade to another track over duration seconds.\n * Fades out current and fades in the new track simultaneously.\n */\n crossfadeTo(name: string, duration: number, loop = true): void {\n if (!this.ctx || !this.output) return;\n const buffer = this.buffers.get(name);\n if (!buffer) return;\n\n const now = this.ctx.currentTime;\n\n // Fade out current\n if (this.currentGain && this.currentSource) {\n const oldGain = this.currentGain;\n const oldSource = this.currentSource;\n oldGain.gain.setValueAtTime(oldGain.gain.value, now);\n oldGain.gain.linearRampToValueAtTime(0, now + duration);\n // Schedule stop after fade\n try {\n oldSource.stop(now + duration);\n } catch {\n // Already stopped\n }\n }\n\n // Start new track fading in\n this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {\n g.gain.setValueAtTime(0, now);\n g.gain.linearRampToValueAtTime(1, now + duration);\n });\n }\n\n private startTrack(\n ctx: AudioContextLike,\n output: GainNodeLike,\n name: string,\n buffer: AudioBufferLike,\n loop: boolean,\n prime: (gain: GainNodeLike) => void,\n ): void {\n const source = ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = loop;\n\n const gain = ctx.createGain();\n prime(gain);\n source.connect(gain);\n gain.connect(output);\n\n source.start();\n this.currentSource = source;\n this.currentGain = gain;\n this.currentName = name;\n\n setSourceEndHandler(source, () => {\n if (this.currentSource === source) {\n this.currentSource = null;\n this.currentGain = null;\n this.currentName = null;\n }\n gain.disconnect();\n });\n }\n\n private stopInternal(): void {\n if (this.currentSource) {\n try {\n this.currentSource.stop();\n } catch {\n // Already stopped\n }\n }\n if (this.currentGain) {\n this.currentGain.disconnect();\n }\n this.currentSource = null;\n this.currentGain = null;\n this.currentName = null;\n }\n}\n","import type { AudioBufferLike, AudioContextLike, GainNodeLike } from './audio-manager.js';\nimport { setSourceEndHandler } from './audio-manager.js';\n\n/** Options for playing a sound effect. */\nexport interface PlaySFXOptions {\n /** Playback volume (0-1). Default: 1. */\n volume?: number;\n /** Playback rate multiplier. Default: 1. Applied only when the audio node exposes a `playbackRate` param. */\n rate?: number;\n /** Whether to loop. Default: false. */\n loop?: boolean;\n /** Seconds to wait before starting, on the context clock. Default: 0 (start at once). Non-finite or non-positive values start at once. */\n delay?: number;\n}\n\n/** A handle to a playing SFX instance. */\nexport interface SFXHandle {\n /** Stop playback. */\n stop(): void;\n}\n\n/** Tracks an active playing source. */\ninterface ActiveSource {\n name: string;\n stop(): void;\n}\n\n/**\n * SFX pool — pre-decoded audio buffers with polyphony management.\n * When max polyphony is reached, the oldest sound is killed.\n */\nexport class SFXPool {\n private buffers = new Map<string, AudioBufferLike>();\n private active: ActiveSource[] = [];\n private ctx: AudioContextLike | null = null;\n private output: GainNodeLike | null = null;\n private maxPolyphony: number;\n\n constructor(maxPolyphony = 16) {\n if (maxPolyphony <= 0) throw new Error('SFXPool: maxPolyphony must be > 0');\n this.maxPolyphony = maxPolyphony;\n }\n\n /** Connect to an AudioContext and output GainNode. */\n connect(ctx: AudioContextLike, output: GainNodeLike): void {\n this.ctx = ctx;\n this.output = output;\n }\n\n /** Register a pre-decoded audio buffer. */\n register(name: string, buffer: AudioBufferLike): void {\n this.buffers.set(name, buffer);\n }\n\n /** Unregister a buffer. */\n unregister(name: string): void {\n this.buffers.delete(name);\n }\n\n /** Check if a buffer is registered. */\n has(name: string): boolean {\n return this.buffers.has(name);\n }\n\n /** Number of registered buffers. */\n get size(): number {\n return this.buffers.size;\n }\n\n /** Number of currently active sounds. */\n get activeCount(): number {\n return this.active.length;\n }\n\n /** Play a registered sound. Returns a handle, or null if not registered/no context. */\n play(name: string, opts?: PlaySFXOptions): SFXHandle | null {\n const buffer = this.buffers.get(name);\n if (!buffer || !this.ctx || !this.output) return null;\n\n // Kill oldest if at max polyphony\n while (this.active.length >= this.maxPolyphony) {\n const oldest = this.active.shift();\n oldest?.stop();\n }\n\n const source = this.ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = opts?.loop ?? false;\n\n // Apply playback rate when the injected node exposes the param (Web Audio shape).\n const rateParam = source.playbackRate;\n if (rateParam && opts?.rate !== undefined) {\n rateParam.value = opts.rate;\n }\n\n // Create a per-source gain for volume control\n const gain = this.ctx.createGain();\n gain.gain.value = opts?.volume ?? 1;\n source.connect(gain);\n gain.connect(this.output);\n\n const entry: ActiveSource = {\n name,\n stop() {\n try {\n source.stop();\n } catch {\n // Already stopped\n }\n gain.disconnect();\n },\n };\n\n this.active.push(entry);\n\n // Clean up when playback ends\n setSourceEndHandler(source, () => {\n const idx = this.active.indexOf(entry);\n if (idx !== -1) {\n this.active.splice(idx, 1);\n }\n gain.disconnect();\n });\n\n const delay = opts?.delay;\n if (delay !== undefined && Number.isFinite(delay) && delay > 0) {\n source.start(this.ctx.currentTime + delay);\n } else {\n source.start();\n }\n\n return {\n stop: () => {\n entry.stop();\n const idx = this.active.indexOf(entry);\n if (idx !== -1) {\n this.active.splice(idx, 1);\n }\n },\n };\n }\n\n /** Stop all active sounds. */\n stopAll(): void {\n for (const entry of this.active) {\n entry.stop();\n }\n this.active.length = 0;\n }\n}\n","import type { PCMBufferLike } from './audio-manager.js';\n\nexport type SynthWaveform = 'sine' | 'square' | 'saw' | 'noise';\n\nexport interface SynthEnvelope {\n /** Seconds from silence to full level. */\n attack: number;\n /** Seconds from full level down to `sustain`. */\n decay: number;\n /** Level (0–1) held after the decay until the release starts. */\n sustain: number;\n /** Seconds of fade to silence, counted back from the end of the sound. */\n release: number;\n}\n\nexport interface SynthSound {\n wave: SynthWaveform;\n /** Hz at the start. Ignored by `noise`. */\n frequency: number;\n /** Hz at the end, reached by a linear sweep from `frequency`. Default: `frequency` (no sweep). */\n endFrequency?: number;\n /** Seconds. */\n duration: number;\n /** Default: `{ attack: 0, decay: 0, sustain: 1, release: 0 }` (flat). */\n envelope?: SynthEnvelope;\n /** Peak amplitude (0–1). Default 1. */\n volume?: number;\n /** 32-bit seed for `noise`; the same seed renders the same samples. Default 1. */\n seed?: number;\n}\n\nconst TWO_PI = Math.PI * 2;\n\n/** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */\nexport function synthSampleCount(duration: number, sampleRate: number): number {\n if (!Number.isFinite(duration) || duration < 0) return 0;\n return Math.ceil(duration * sampleRate);\n}\n\n/**\n * Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples\n * written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.\n */\nexport function renderSynth(sound: SynthSound, sampleRate: number, out: Float32Array): number {\n if (!Number.isFinite(sampleRate) || sampleRate <= 0) return 0;\n const duration = sound.duration;\n const n = Math.min(out.length, synthSampleCount(duration, sampleRate));\n const wave = sound.wave;\n const volume = sound.volume ?? 1;\n const f0 = sound.frequency;\n const sweep = ((sound.endFrequency ?? f0) - f0) / duration;\n const env = sound.envelope;\n const attack = env ? env.attack : 0;\n const decay = env ? env.decay : 0;\n const sustain = env ? env.sustain : 1;\n const release = env ? env.release : 0;\n const decayEnd = attack + decay;\n const releaseStart = duration - release;\n const dt = 1 / sampleRate;\n let phase = 0;\n let rng = (sound.seed ?? 1) | 0 || 1;\n\n for (let i = 0; i < n; i++) {\n const t = i * dt;\n let osc: number;\n switch (wave) {\n case 'sine':\n osc = Math.sin(TWO_PI * phase);\n break;\n case 'square':\n osc = phase < 0.5 ? 1 : -1;\n break;\n case 'saw':\n osc = 2 * phase - 1;\n break;\n default:\n rng ^= rng << 13;\n rng ^= rng >>> 17;\n rng ^= rng << 5;\n osc = (rng >>> 0) / 2147483648 - 1;\n break;\n }\n let gain =\n t < attack ? t / attack : t < decayEnd ? 1 - ((1 - sustain) * (t - attack)) / decay : sustain;\n if (release > 0 && t >= releaseStart) gain *= (duration - t) / release;\n out[i] = osc * gain * volume;\n phase += (f0 + sweep * t) * dt;\n if (phase >= 1) phase -= Math.floor(phase);\n }\n return n;\n}\n\n/** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */\nexport function fillPCMBuffer(buffer: PCMBufferLike, pcm: Float32Array): void {\n for (let c = 0; c < buffer.numberOfChannels; c++) buffer.copyToChannel(pcm, c);\n}\n"],"mappings":";;AAsEA,SAAgB,oBAAoB,QAAmC,SAA2B;CAChG,IAAI,aAAa,QACf,OAAO,UAAU;MAEjB,OAAO,UAAU;AAErB;;;;;AASA,IAAa,eAAb,MAA0B;CACxB,MAAuC;;CAGvC,IAAI,QAAoB;EACtB,IAAI,CAAC,KAAK,KAAK,OAAO;EACtB,OAAO,KAAK,IAAI,UAAU,WAAW,WAAW,KAAK,IAAI;CAC3D;;CAGA,IAAI,UAAmC;EACrC,OAAO,KAAK;CACd;;CAGA,IAAI,cAAsB;EACxB,OAAO,KAAK,KAAK,eAAe;CAClC;;CAGA,KAAK,SAAuC;EAC1C,IAAI,KAAK,KAAK;EACd,KAAK,MAAM,QAAQ;CACrB;;CAGA,MAAM,UAAyB;EAC7B,IAAI,KAAK,KAAK,UAAU,WACtB,MAAM,KAAK,IAAI,QAAQ;CAE3B;;CAGA,MAAM,SAAwB;EAC5B,IAAI,KAAK,KAAK,UAAU,aACtB,MAAM,KAAK,IAAI,OAAO;CAE1B;;CAGA,MAAM,QAAuB;EAC3B,IAAI,KAAK,KAAK;GACZ,MAAM,KAAK,IAAI,MAAM;GACrB,KAAK,MAAM;EACb;CACF;AACF;;;;;;ACjHA,SAAgB,eAAe,KAAkD;CAC/E,MAAM,aAAa,IAAI,WAAW;CAClC,WAAW,KAAK,QAAQ;CACxB,WAAW,QAAQ,IAAI,WAAW;CAElC,MAAM,UAAU,IAAI,WAAW;CAC/B,QAAQ,KAAK,QAAQ;CACrB,QAAQ,QAAQ,UAAU;CAE1B,MAAM,YAAY,IAAI,WAAW;CACjC,UAAU,KAAK,QAAQ;CAC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,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;EAC1B,MAAM,IAAI,IAAI;EACd,IAAI;EACJ,QAAQ,MAAR;GACE,KAAK;IACH,MAAM,KAAK,IAAI,SAAS,KAAK;IAC7B;GACF,KAAK;IACH,MAAM,QAAQ,KAAM,IAAI;IACxB;GACF,KAAK;IACH,MAAM,IAAI,QAAQ;IAClB;GACF;IACE,OAAO,OAAO;IACd,OAAO,QAAQ;IACf,OAAO,OAAO;IACd,OAAO,QAAQ,KAAK,aAAa;EAErC;EACA,IAAI,OACF,IAAI,SAAS,IAAI,SAAS,IAAI,WAAW,KAAM,IAAI,YAAY,IAAI,UAAW,QAAQ;EACxF,IAAI,UAAU,KAAK,KAAK,cAAc,SAAS,WAAW,KAAK;EAC/D,IAAI,KAAK,MAAM,OAAO;EACtB,UAAU,KAAK,QAAQ,KAAK;EAC5B,IAAI,SAAS,GAAG,SAAS,KAAK,MAAM,KAAK;CAC3C;CACA,OAAO;AACT;;AAGA,SAAgB,cAAc,QAAuB,KAAyB;CAC5E,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,kBAAkB,KAAK,OAAO,cAAc,KAAK,CAAC;AAC/E"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/audio-manager.ts","../src/channels.ts","../src/music.ts","../src/sfx-pool.ts","../src/synth.ts"],"sourcesContent":["/**\n * Minimal interfaces for the Web Audio API subset we use.\n * At runtime these are provided by react-native-audio-api.\n */\n\nexport interface AudioDestinationNodeLike {\n readonly channelCount: number;\n}\n\nexport interface GainNodeLike {\n readonly gain: AudioParamLike;\n connect(dest: AudioDestinationNodeLike | GainNodeLike): void;\n disconnect(): void;\n}\n\nexport interface AudioParamLike {\n value: number;\n setValueAtTime(value: number, time: number): void;\n linearRampToValueAtTime(value: number, time: number): void;\n}\n\nexport interface AudioBufferLike {\n readonly duration: number;\n readonly numberOfChannels: number;\n readonly sampleRate: number;\n readonly length: number;\n}\n\n/** Writable `AudioBuffer` shape (`copyToChannel` exists on the DOM and in react-native-audio-api). */\nexport interface PCMBufferLike extends AudioBufferLike {\n copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;\n}\n\nexport interface AudioBufferSourceNodeLike {\n buffer: AudioBufferLike | null;\n loop: boolean;\n /**\n * Playback-rate param (Web Audio shape). Optional — not every injected node\n * exposes it; `SFXPool.play`'s `rate` option is a no-op when this is absent.\n */\n readonly playbackRate?: { value: number };\n connect(dest: GainNodeLike | AudioDestinationNodeLike): void;\n disconnect(): void;\n start(when?: number): void;\n stop(when?: number): void;\n onended: ((this: AudioBufferSourceNodeLike, ev: unknown) => void) | null;\n /**\n * End-of-playback callback as `react-native-audio-api` spells it; the DOM spells it\n * `onended`. A node exposes one or the other — register through `setSourceEndHandler`.\n */\n onEnded?: ((ev: unknown) => void) | null;\n}\n\nexport interface AudioContextLike {\n readonly state: 'suspended' | 'running' | 'closed';\n readonly currentTime: number;\n readonly destination: AudioDestinationNodeLike;\n createGain(): GainNodeLike;\n createBufferSource(): AudioBufferSourceNodeLike;\n /**\n * Allocates a writable buffer for `fillPCMBuffer`. Optional so hand-written contexts\n * keep type-checking.\n */\n createBuffer?(numberOfChannels: number, length: number, sampleRate: number): PCMBufferLike;\n resume(): Promise<void>;\n suspend(): Promise<void>;\n close(): Promise<void>;\n}\n\n/** Registers the end-of-playback handler on whichever accessor the node exposes. */\nexport function setSourceEndHandler(source: AudioBufferSourceNodeLike, handler: () => void): void {\n if ('onEnded' in source) {\n source.onEnded = handler;\n } else {\n source.onended = handler;\n }\n}\n\n/** Audio context state. */\nexport type AudioState = 'uninitialized' | 'running' | 'suspended' | 'closed';\n\n/**\n * AudioManager — manages the AudioContext lifecycle.\n * Wraps react-native-audio-api's AudioContext.\n */\nexport class AudioManager {\n private ctx: AudioContextLike | null = null;\n\n /** Current audio state. */\n get state(): AudioState {\n if (!this.ctx) return 'uninitialized';\n return this.ctx.state === 'closed' ? 'closed' : this.ctx.state;\n }\n\n /** The underlying AudioContext, or null if not initialized. */\n get context(): AudioContextLike | null {\n return this.ctx;\n }\n\n /** Current time from the AudioContext. */\n get currentTime(): number {\n return this.ctx?.currentTime ?? 0;\n }\n\n /** Initialize with a factory that creates the native AudioContext. */\n init(factory: () => AudioContextLike): void {\n if (this.ctx) return;\n this.ctx = factory();\n }\n\n /** Suspend audio. Call from your own background handler — no automatic wiring. */\n async suspend(): Promise<void> {\n if (this.ctx?.state === 'running') {\n await this.ctx.suspend();\n }\n }\n\n /** Resume audio. Call from your own foreground handler — no automatic wiring. */\n async resume(): Promise<void> {\n if (this.ctx?.state === 'suspended') {\n await this.ctx.resume();\n }\n }\n\n /** Close and dispose the AudioContext. */\n async close(): Promise<void> {\n if (this.ctx) {\n await this.ctx.close();\n this.ctx = null;\n }\n }\n}\n","import type { AudioContextLike, GainNodeLike } from './audio-manager.js';\n\n/** A volume channel that wraps a GainNode. */\nexport interface Channel {\n readonly name: string;\n /** Current volume (0.0 - 1.0). */\n volume: number;\n /** The underlying GainNode. */\n readonly node: GainNodeLike;\n}\n\n/** Standard channel names. */\nexport type ChannelName = 'master' | 'sfx' | 'music';\n\n/**\n * Creates volume channels connected: sfx → master, music → master, master → destination.\n * Returns a map of channels by name.\n */\nexport function createChannels(ctx: AudioContextLike): Map<ChannelName, Channel> {\n const masterGain = ctx.createGain();\n masterGain.gain.value = 1;\n masterGain.connect(ctx.destination);\n\n const sfxGain = ctx.createGain();\n sfxGain.gain.value = 1;\n sfxGain.connect(masterGain);\n\n const musicGain = ctx.createGain();\n musicGain.gain.value = 1;\n musicGain.connect(masterGain);\n\n const channels = new Map<ChannelName, Channel>();\n\n channels.set('master', createChannel('master', masterGain));\n channels.set('sfx', createChannel('sfx', sfxGain));\n channels.set('music', createChannel('music', musicGain));\n\n return channels;\n}\n\nfunction createChannel(name: string, node: GainNodeLike): Channel {\n let vol = 1;\n return {\n name,\n get volume() {\n return vol;\n },\n set volume(v: number) {\n vol = Math.max(0, Math.min(1, v));\n node.gain.value = vol;\n },\n node,\n };\n}\n","import type {\n AudioBufferLike,\n AudioBufferSourceNodeLike,\n AudioContextLike,\n GainNodeLike,\n} from './audio-manager.js';\nimport { setSourceEndHandler } from './audio-manager.js';\n\n/**\n * Music player — one track at a time, with crossfade support.\n * Loops by default.\n */\nexport class Music {\n private ctx: AudioContextLike | null = null;\n private output: GainNodeLike | null = null;\n private buffers = new Map<string, AudioBufferLike>();\n private currentSource: AudioBufferSourceNodeLike | null = null;\n private currentGain: GainNodeLike | null = null;\n private currentName: string | null = null;\n private fadingSource: AudioBufferSourceNodeLike | null = null;\n private fadingGain: GainNodeLike | null = null;\n\n /** Name of the currently playing track, or null. */\n get playing(): string | null {\n return this.currentName;\n }\n\n /** Connect to an AudioContext and output gain node. */\n connect(ctx: AudioContextLike, output: GainNodeLike): void {\n this.ctx = ctx;\n this.output = output;\n }\n\n /** Register a music track buffer. */\n register(name: string, buffer: AudioBufferLike): void {\n this.buffers.set(name, buffer);\n }\n\n /** Play a track. Stops any currently playing track. Loops by default. */\n play(name: string, loop = true): void {\n if (!this.ctx || !this.output) return;\n const buffer = this.buffers.get(name);\n if (!buffer) return;\n\n this.stopInternal();\n\n this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {\n g.gain.value = 1;\n });\n }\n\n /** Stop the current track and any track still fading out from a crossfade. */\n stop(): void {\n this.stopInternal();\n }\n\n /**\n * Crossfade to another track over duration seconds.\n * Fades out current and fades in the new track simultaneously.\n * A track still fading out from an earlier crossfade is stopped at once.\n */\n crossfadeTo(name: string, duration: number, loop = true): void {\n if (!this.ctx || !this.output) return;\n const buffer = this.buffers.get(name);\n if (!buffer) return;\n\n const now = this.ctx.currentTime;\n\n // Fade out current\n if (this.currentGain && this.currentSource) {\n const oldGain = this.currentGain;\n const oldSource = this.currentSource;\n oldGain.gain.setValueAtTime(oldGain.gain.value, now);\n oldGain.gain.linearRampToValueAtTime(0, now + duration);\n // Schedule stop after fade\n try {\n oldSource.stop(now + duration);\n } catch {\n // Already stopped\n }\n this.stopFading();\n this.fadingSource = oldSource;\n this.fadingGain = oldGain;\n }\n\n // Start new track fading in\n this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {\n g.gain.setValueAtTime(0, now);\n g.gain.linearRampToValueAtTime(1, now + duration);\n });\n }\n\n private startTrack(\n ctx: AudioContextLike,\n output: GainNodeLike,\n name: string,\n buffer: AudioBufferLike,\n loop: boolean,\n prime: (gain: GainNodeLike) => void,\n ): void {\n const source = ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = loop;\n\n const gain = ctx.createGain();\n prime(gain);\n source.connect(gain);\n gain.connect(output);\n\n source.start();\n this.currentSource = source;\n this.currentGain = gain;\n this.currentName = name;\n\n setSourceEndHandler(source, () => {\n if (this.currentSource === source) {\n this.currentSource = null;\n this.currentGain = null;\n this.currentName = null;\n }\n if (this.fadingSource === source) {\n this.fadingSource = null;\n this.fadingGain = null;\n }\n gain.disconnect();\n });\n }\n\n private stopInternal(): void {\n if (this.currentSource) {\n try {\n this.currentSource.stop();\n } catch {\n // Already stopped\n }\n }\n if (this.currentGain) {\n this.currentGain.disconnect();\n }\n this.currentSource = null;\n this.currentGain = null;\n this.currentName = null;\n this.stopFading();\n }\n\n private stopFading(): void {\n if (this.fadingSource) {\n try {\n this.fadingSource.stop();\n } catch {\n // Already stopped\n }\n }\n if (this.fadingGain) {\n this.fadingGain.disconnect();\n }\n this.fadingSource = null;\n this.fadingGain = null;\n }\n}\n","import type { AudioBufferLike, AudioContextLike, GainNodeLike } from './audio-manager.js';\nimport { setSourceEndHandler } from './audio-manager.js';\n\n/** Options for playing a sound effect. */\nexport interface PlaySFXOptions {\n /** Playback volume (0-1). Default: 1. */\n volume?: number;\n /** Playback rate multiplier. Default: 1. Applied only when the audio node exposes a `playbackRate` param. */\n rate?: number;\n /** Whether to loop. Default: false. */\n loop?: boolean;\n /** Seconds to wait before starting, on the context clock. Default: 0 (start at once). Non-finite or non-positive values start at once. */\n delay?: number;\n}\n\n/** A handle to a playing SFX instance. */\nexport interface SFXHandle {\n /** Stop playback. */\n stop(): void;\n}\n\n/** Tracks an active playing source. */\ninterface ActiveSource {\n name: string;\n stop(): void;\n}\n\n/**\n * SFX pool — pre-decoded audio buffers with polyphony management.\n * When max polyphony is reached, the oldest sound is killed.\n */\nexport class SFXPool {\n private buffers = new Map<string, AudioBufferLike>();\n private active: ActiveSource[] = [];\n private ctx: AudioContextLike | null = null;\n private output: GainNodeLike | null = null;\n private maxPolyphony: number;\n\n constructor(maxPolyphony = 16) {\n if (maxPolyphony <= 0) throw new Error('SFXPool: maxPolyphony must be > 0');\n this.maxPolyphony = maxPolyphony;\n }\n\n /** Connect to an AudioContext and output GainNode. */\n connect(ctx: AudioContextLike, output: GainNodeLike): void {\n this.ctx = ctx;\n this.output = output;\n }\n\n /** Register a pre-decoded audio buffer. */\n register(name: string, buffer: AudioBufferLike): void {\n this.buffers.set(name, buffer);\n }\n\n /** Unregister a buffer. */\n unregister(name: string): void {\n this.buffers.delete(name);\n }\n\n /** Check if a buffer is registered. */\n has(name: string): boolean {\n return this.buffers.has(name);\n }\n\n /** Number of registered buffers. */\n get size(): number {\n return this.buffers.size;\n }\n\n /** Number of currently active sounds. */\n get activeCount(): number {\n return this.active.length;\n }\n\n /** Play a registered sound. Returns a handle, or null if not registered/no context. */\n play(name: string, opts?: PlaySFXOptions): SFXHandle | null {\n const buffer = this.buffers.get(name);\n if (!buffer || !this.ctx || !this.output) return null;\n\n // Kill oldest if at max polyphony\n while (this.active.length >= this.maxPolyphony) {\n const oldest = this.active.shift();\n oldest?.stop();\n }\n\n const source = this.ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = opts?.loop ?? false;\n\n // Apply playback rate when the injected node exposes the param (Web Audio shape).\n const rateParam = source.playbackRate;\n if (rateParam && opts?.rate !== undefined) {\n rateParam.value = opts.rate;\n }\n\n // Create a per-source gain for volume control\n const gain = this.ctx.createGain();\n gain.gain.value = opts?.volume ?? 1;\n source.connect(gain);\n gain.connect(this.output);\n\n const entry: ActiveSource = {\n name,\n stop() {\n try {\n source.stop();\n } catch {\n // Already stopped\n }\n gain.disconnect();\n },\n };\n\n this.active.push(entry);\n\n // Clean up when playback ends\n setSourceEndHandler(source, () => {\n const idx = this.active.indexOf(entry);\n if (idx !== -1) {\n this.active.splice(idx, 1);\n }\n gain.disconnect();\n });\n\n const delay = opts?.delay;\n if (delay !== undefined && Number.isFinite(delay) && delay > 0) {\n source.start(this.ctx.currentTime + delay);\n } else {\n source.start();\n }\n\n return {\n stop: () => {\n entry.stop();\n const idx = this.active.indexOf(entry);\n if (idx !== -1) {\n this.active.splice(idx, 1);\n }\n },\n };\n }\n\n /** Stop all active sounds. */\n stopAll(): void {\n for (const entry of this.active) {\n entry.stop();\n }\n this.active.length = 0;\n }\n}\n","import type { PCMBufferLike } from './audio-manager.js';\n\nexport type SynthWaveform = 'sine' | 'square' | 'saw' | 'noise';\n\nexport interface SynthEnvelope {\n /** Seconds from silence to full level. */\n attack: number;\n /** Seconds from full level down to `sustain`. */\n decay: number;\n /** Level (0–1) held after the decay until the release starts. */\n sustain: number;\n /** Seconds of fade to silence, counted back from the end of the sound. */\n release: number;\n}\n\nexport interface SynthSound {\n wave: SynthWaveform;\n /** Hz at the start. Ignored by `noise`. */\n frequency: number;\n /** Hz at the end, reached by a linear sweep from `frequency`. Default: `frequency` (no sweep). */\n endFrequency?: number;\n /** Seconds. */\n duration: number;\n /** Default: `{ attack: 0, decay: 0, sustain: 1, release: 0 }` (flat). */\n envelope?: SynthEnvelope;\n /** Peak amplitude (0–1). Default 1. */\n volume?: number;\n /** 32-bit seed for `noise`; the same seed renders the same samples. Default 1. */\n seed?: number;\n}\n\nconst TWO_PI = Math.PI * 2;\n\n/** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */\nexport function synthSampleCount(duration: number, sampleRate: number): number {\n if (!Number.isFinite(duration) || duration < 0) return 0;\n return Math.ceil(duration * sampleRate);\n}\n\n/**\n * Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples\n * written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.\n */\nexport function renderSynth(sound: SynthSound, sampleRate: number, out: Float32Array): number {\n if (!Number.isFinite(sampleRate) || sampleRate <= 0) return 0;\n const duration = sound.duration;\n const n = Math.min(out.length, synthSampleCount(duration, sampleRate));\n const wave = sound.wave;\n const volume = sound.volume ?? 1;\n const f0 = sound.frequency;\n const sweep = ((sound.endFrequency ?? f0) - f0) / duration;\n const env = sound.envelope;\n const attack = env ? env.attack : 0;\n const decay = env ? env.decay : 0;\n const sustain = env ? env.sustain : 1;\n const release = env ? env.release : 0;\n const decayEnd = attack + decay;\n const releaseStart = duration - release;\n const dt = 1 / sampleRate;\n let phase = 0;\n let rng = (sound.seed ?? 1) | 0 || 1;\n\n for (let i = 0; i < n; i++) {\n const t = i * dt;\n let osc: number;\n switch (wave) {\n case 'sine':\n osc = Math.sin(TWO_PI * phase);\n break;\n case 'square':\n osc = phase < 0.5 ? 1 : -1;\n break;\n case 'saw':\n osc = 2 * phase - 1;\n break;\n default:\n rng ^= rng << 13;\n rng ^= rng >>> 17;\n rng ^= rng << 5;\n osc = (rng >>> 0) / 2147483648 - 1;\n break;\n }\n let gain =\n t < attack ? t / attack : t < decayEnd ? 1 - ((1 - sustain) * (t - attack)) / decay : sustain;\n if (release > 0 && t >= releaseStart) gain *= (duration - t) / release;\n out[i] = osc * gain * volume;\n phase += (f0 + sweep * t) * dt;\n if (phase >= 1) phase -= Math.floor(phase);\n }\n return n;\n}\n\n/** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */\nexport function fillPCMBuffer(buffer: PCMBufferLike, pcm: Float32Array): void {\n for (let c = 0; c < buffer.numberOfChannels; c++) buffer.copyToChannel(pcm, c);\n}\n"],"mappings":";;AAsEA,SAAgB,oBAAoB,QAAmC,SAA2B;CAChG,IAAI,aAAa,QACf,OAAO,UAAU;MAEjB,OAAO,UAAU;AAErB;;;;;AASA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I,IAAI,GAAG,IAAI,GAAG,KAAK;EAC1B,MAAM,IAAI,IAAI;EACd,IAAI;EACJ,QAAQ,MAAR;GACE,KAAK;IACH,MAAM,KAAK,IAAI,SAAS,KAAK;IAC7B;GACF,KAAK;IACH,MAAM,QAAQ,KAAM,IAAI;IACxB;GACF,KAAK;IACH,MAAM,IAAI,QAAQ;IAClB;GACF;IACE,OAAO,OAAO;IACd,OAAO,QAAQ;IACf,OAAO,OAAO;IACd,OAAO,QAAQ,KAAK,aAAa;EAErC;EACA,IAAI,OACF,IAAI,SAAS,IAAI,SAAS,IAAI,WAAW,KAAM,IAAI,YAAY,IAAI,UAAW,QAAQ;EACxF,IAAI,UAAU,KAAK,KAAK,cAAc,SAAS,WAAW,KAAK;EAC/D,IAAI,KAAK,MAAM,OAAO;EACtB,UAAU,KAAK,QAAQ,KAAK;EAC5B,IAAI,SAAS,GAAG,SAAS,KAAK,MAAM,KAAK;CAC3C;CACA,OAAO;AACT;;AAGA,SAAgB,cAAc,QAAuB,KAAyB;CAC5E,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,kBAAkB,KAAK,OAAO,cAAc,KAAK,CAAC;AAC/E"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flare-engine/audio",
3
- "version": "0.4.11",
3
+ "version": "0.4.12",
4
4
  "description": "AudioManager, SFX pool, music crossfade",
5
5
  "keywords": ["flare-engine", "audio", "sfx", "music", "react-native", "typescript"],
6
6
  "license": "Apache-2.0",