@flare-engine/audio 0.4.8 → 0.4.11

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @flare-engine/audio
2
2
 
3
- Web-Audio-shaped runtime audio — `AudioManager` (init / suspend / resume), `SFXPool` (pre-decoded buffers + polyphony cap), `Music` (single-track with crossfade), `createChannels` (master / sfx / music gain mixer). Lifecycle is manual: call `suspend()`/`resume()` from your own background/foreground handler (see below).
3
+ Web-Audio-shaped runtime audio — `AudioManager` (init / suspend / resume), `SFXPool` (pre-decoded buffers + polyphony cap), `Music` (single-track with crossfade), `createChannels` (master / sfx / music gain mixer), `renderSynth` (procedural SFX to PCM). Lifecycle is manual: call `suspend()`/`resume()` from your own background/foreground handler (see below).
4
4
 
5
5
  ## Install
6
6
 
@@ -37,6 +37,29 @@ sfx.connect(ctx, channels.get('sfx')!.node);
37
37
  // Register pre-decoded buffers (decode with react-native-audio-api), then play.
38
38
  sfx.register('shoot', shootBuffer);
39
39
  sfx.play('shoot', { volume: 0.8, rate: 1.25 });
40
+ sfx.play('hit', { delay: 0.35 }); // start 350 ms from now on the audio clock
41
+ ```
42
+
43
+ ## Synthesised SFX
44
+
45
+ `renderSynth` renders a described sound (sine / square / saw / noise, ADSR envelope, linear frequency sweep) into a caller-owned mono `Float32Array`; `fillPCMBuffer` copies it into a buffer the context created.
46
+
47
+ ```ts
48
+ import { fillPCMBuffer, renderSynth, synthSampleCount } from '@flare-engine/audio';
49
+ import type { AudioContextLike, SFXPool } from '@flare-engine/audio';
50
+
51
+ declare const ctx: AudioContextLike;
52
+ declare const sfx: SFXPool;
53
+
54
+ const rate = 44100;
55
+ const n = synthSampleCount(0.15, rate);
56
+ const pcm = new Float32Array(n);
57
+ renderSynth({ wave: 'square', frequency: 880, endFrequency: 220, duration: 0.15 }, rate, pcm);
58
+ const buffer = ctx.createBuffer?.(1, n, rate); // optional on AudioContextLike
59
+ if (buffer) {
60
+ fillPCMBuffer(buffer, pcm);
61
+ sfx.register('blip', buffer);
62
+ }
40
63
  ```
41
64
 
42
65
  ## Lifecycle (manual)
package/dist/index.d.mts CHANGED
@@ -21,6 +21,10 @@ interface AudioBufferLike {
21
21
  readonly sampleRate: number;
22
22
  readonly length: number;
23
23
  }
24
+ /** Writable `AudioBuffer` shape (`copyToChannel` exists on the DOM and in react-native-audio-api). */
25
+ interface PCMBufferLike extends AudioBufferLike {
26
+ copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;
27
+ }
24
28
  interface AudioBufferSourceNodeLike {
25
29
  buffer: AudioBufferLike | null;
26
30
  loop: boolean;
@@ -36,6 +40,11 @@ interface AudioBufferSourceNodeLike {
36
40
  start(when?: number): void;
37
41
  stop(when?: number): void;
38
42
  onended: ((this: AudioBufferSourceNodeLike, ev: unknown) => void) | null;
43
+ /**
44
+ * End-of-playback callback as `react-native-audio-api` spells it; the DOM spells it
45
+ * `onended`. A node exposes one or the other — register through `setSourceEndHandler`.
46
+ */
47
+ onEnded?: ((ev: unknown) => void) | null;
39
48
  }
40
49
  interface AudioContextLike {
41
50
  readonly state: 'suspended' | 'running' | 'closed';
@@ -43,6 +52,11 @@ interface AudioContextLike {
43
52
  readonly destination: AudioDestinationNodeLike;
44
53
  createGain(): GainNodeLike;
45
54
  createBufferSource(): AudioBufferSourceNodeLike;
55
+ /**
56
+ * Allocates a writable buffer for `fillPCMBuffer`. Optional so hand-written contexts
57
+ * keep type-checking.
58
+ */
59
+ createBuffer?(numberOfChannels: number, length: number, sampleRate: number): PCMBufferLike;
46
60
  resume(): Promise<void>;
47
61
  suspend(): Promise<void>;
48
62
  close(): Promise<void>;
@@ -111,6 +125,7 @@ export declare class Music {
111
125
  * Fades out current and fades in the new track simultaneously.
112
126
  */
113
127
  crossfadeTo(name: string, duration: number, loop?: boolean): void;
128
+ private startTrack;
114
129
  private stopInternal;
115
130
  }
116
131
  /** Options for playing a sound effect. */
@@ -121,6 +136,8 @@ interface PlaySFXOptions {
121
136
  rate?: number;
122
137
  /** Whether to loop. Default: false. */
123
138
  loop?: boolean;
139
+ /** Seconds to wait before starting, on the context clock. Default: 0 (start at once). Non-finite or non-positive values start at once. */
140
+ delay?: number;
124
141
  }
125
142
  /** A handle to a playing SFX instance. */
126
143
  interface SFXHandle {
@@ -155,5 +172,40 @@ export declare class SFXPool {
155
172
  /** Stop all active sounds. */
156
173
  stopAll(): void;
157
174
  }
158
- export type { AudioBufferLike, AudioBufferSourceNodeLike, AudioContextLike, AudioDestinationNodeLike, AudioParamLike, AudioState, Channel, ChannelName, GainNodeLike, PlaySFXOptions, SFXHandle };
175
+ type SynthWaveform = 'sine' | 'square' | 'saw' | 'noise';
176
+ interface SynthEnvelope {
177
+ /** Seconds from silence to full level. */
178
+ attack: number;
179
+ /** Seconds from full level down to `sustain`. */
180
+ decay: number;
181
+ /** Level (0–1) held after the decay until the release starts. */
182
+ sustain: number;
183
+ /** Seconds of fade to silence, counted back from the end of the sound. */
184
+ release: number;
185
+ }
186
+ interface SynthSound {
187
+ wave: SynthWaveform;
188
+ /** Hz at the start. Ignored by `noise`. */
189
+ frequency: number;
190
+ /** Hz at the end, reached by a linear sweep from `frequency`. Default: `frequency` (no sweep). */
191
+ endFrequency?: number;
192
+ /** Seconds. */
193
+ duration: number;
194
+ /** Default: `{ attack: 0, decay: 0, sustain: 1, release: 0 }` (flat). */
195
+ envelope?: SynthEnvelope;
196
+ /** Peak amplitude (0–1). Default 1. */
197
+ volume?: number;
198
+ /** 32-bit seed for `noise`; the same seed renders the same samples. Default 1. */
199
+ seed?: number;
200
+ }
201
+ /** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */
202
+ export declare function synthSampleCount(duration: number, sampleRate: number): number;
203
+ /**
204
+ * Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples
205
+ * written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.
206
+ */
207
+ export declare function renderSynth(sound: SynthSound, sampleRate: number, out: Float32Array): number;
208
+ /** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */
209
+ export declare function fillPCMBuffer(buffer: PCMBufferLike, pcm: Float32Array): void;
210
+ export type { AudioBufferLike, AudioBufferSourceNodeLike, AudioContextLike, AudioDestinationNodeLike, AudioParamLike, AudioState, Channel, ChannelName, GainNodeLike, PCMBufferLike, PlaySFXOptions, SFXHandle, SynthEnvelope, SynthSound, SynthWaveform };
159
211
  //# sourceMappingURL=index.d.mts.map
@@ -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"],"mappings":";;;;UAKiB;WACN;;UAGM;WACN,MAAM;EACf,QAAQ,MAAM,2BAA2B;EACzC;;UAGe;EACf;EACA,eAAe,eAAe;EAC9B,wBAAwB,eAAe;;UAGxB;WACN;WACA;WACA;WACA;;UAGM;EACf,QAAQ;EACR;;;;;WAKS;IAAiB;;EAC1B,QAAQ,MAAM,eAAe;EAC7B;EACA,MAAM;EACN,KAAK;EACL,WAAW,MAAM,2BAA2B;;UAG7B;WACN;WACA;WACA,aAAa;EACtB,cAAc;EACd,sBAAsB;EACtB,UAAU;EACV,WAAW;EACX,SAAS;;;KAIC;;;;;qBAMC;UACH;;MAGJ,SAAS;;MAMT,WAAW;;MAKX;;EAKJ,KAAK,eAAe;;EAMd,WAAW;;EAOX,UAAU;;EAOV,SAAS;;;UClGA;WACN;;EAET;;WAES,MAAM;;;KAIL;;;;;wBAMI,eAAe,KAAK,mBAAmB,IAAI,aAAa;;;;;qBCP3D;UACH;UACA;UACA;UACA;UACA;UACA;;MAGJ;;EAKJ,QAAQ,KAAK,kBAAkB,QAAQ;;EAMvC,SAAS,cAAc,QAAQ;;EAK/B,KAAK,cAAc;;EAgCnB;;;;;EAQA,YAAY,cAAc,kBAAkB;UA+CpC;;;UCxHO;;EAEf;;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;;EA+D3C"}
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"}
package/dist/index.d.ts CHANGED
@@ -21,6 +21,10 @@ interface AudioBufferLike {
21
21
  readonly sampleRate: number;
22
22
  readonly length: number;
23
23
  }
24
+ /** Writable `AudioBuffer` shape (`copyToChannel` exists on the DOM and in react-native-audio-api). */
25
+ interface PCMBufferLike extends AudioBufferLike {
26
+ copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;
27
+ }
24
28
  interface AudioBufferSourceNodeLike {
25
29
  buffer: AudioBufferLike | null;
26
30
  loop: boolean;
@@ -36,6 +40,11 @@ interface AudioBufferSourceNodeLike {
36
40
  start(when?: number): void;
37
41
  stop(when?: number): void;
38
42
  onended: ((this: AudioBufferSourceNodeLike, ev: unknown) => void) | null;
43
+ /**
44
+ * End-of-playback callback as `react-native-audio-api` spells it; the DOM spells it
45
+ * `onended`. A node exposes one or the other — register through `setSourceEndHandler`.
46
+ */
47
+ onEnded?: ((ev: unknown) => void) | null;
39
48
  }
40
49
  interface AudioContextLike {
41
50
  readonly state: 'suspended' | 'running' | 'closed';
@@ -43,6 +52,11 @@ interface AudioContextLike {
43
52
  readonly destination: AudioDestinationNodeLike;
44
53
  createGain(): GainNodeLike;
45
54
  createBufferSource(): AudioBufferSourceNodeLike;
55
+ /**
56
+ * Allocates a writable buffer for `fillPCMBuffer`. Optional so hand-written contexts
57
+ * keep type-checking.
58
+ */
59
+ createBuffer?(numberOfChannels: number, length: number, sampleRate: number): PCMBufferLike;
46
60
  resume(): Promise<void>;
47
61
  suspend(): Promise<void>;
48
62
  close(): Promise<void>;
@@ -111,6 +125,7 @@ export declare class Music {
111
125
  * Fades out current and fades in the new track simultaneously.
112
126
  */
113
127
  crossfadeTo(name: string, duration: number, loop?: boolean): void;
128
+ private startTrack;
114
129
  private stopInternal;
115
130
  }
116
131
  /** Options for playing a sound effect. */
@@ -121,6 +136,8 @@ interface PlaySFXOptions {
121
136
  rate?: number;
122
137
  /** Whether to loop. Default: false. */
123
138
  loop?: boolean;
139
+ /** Seconds to wait before starting, on the context clock. Default: 0 (start at once). Non-finite or non-positive values start at once. */
140
+ delay?: number;
124
141
  }
125
142
  /** A handle to a playing SFX instance. */
126
143
  interface SFXHandle {
@@ -155,5 +172,40 @@ export declare class SFXPool {
155
172
  /** Stop all active sounds. */
156
173
  stopAll(): void;
157
174
  }
158
- export type { AudioBufferLike, AudioBufferSourceNodeLike, AudioContextLike, AudioDestinationNodeLike, AudioParamLike, AudioState, Channel, ChannelName, GainNodeLike, PlaySFXOptions, SFXHandle };
175
+ type SynthWaveform = 'sine' | 'square' | 'saw' | 'noise';
176
+ interface SynthEnvelope {
177
+ /** Seconds from silence to full level. */
178
+ attack: number;
179
+ /** Seconds from full level down to `sustain`. */
180
+ decay: number;
181
+ /** Level (0–1) held after the decay until the release starts. */
182
+ sustain: number;
183
+ /** Seconds of fade to silence, counted back from the end of the sound. */
184
+ release: number;
185
+ }
186
+ interface SynthSound {
187
+ wave: SynthWaveform;
188
+ /** Hz at the start. Ignored by `noise`. */
189
+ frequency: number;
190
+ /** Hz at the end, reached by a linear sweep from `frequency`. Default: `frequency` (no sweep). */
191
+ endFrequency?: number;
192
+ /** Seconds. */
193
+ duration: number;
194
+ /** Default: `{ attack: 0, decay: 0, sustain: 1, release: 0 }` (flat). */
195
+ envelope?: SynthEnvelope;
196
+ /** Peak amplitude (0–1). Default 1. */
197
+ volume?: number;
198
+ /** 32-bit seed for `noise`; the same seed renders the same samples. Default 1. */
199
+ seed?: number;
200
+ }
201
+ /** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */
202
+ export declare function synthSampleCount(duration: number, sampleRate: number): number;
203
+ /**
204
+ * Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples
205
+ * written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.
206
+ */
207
+ export declare function renderSynth(sound: SynthSound, sampleRate: number, out: Float32Array): number;
208
+ /** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */
209
+ export declare function fillPCMBuffer(buffer: PCMBufferLike, pcm: Float32Array): void;
210
+ export type { AudioBufferLike, AudioBufferSourceNodeLike, AudioContextLike, AudioDestinationNodeLike, AudioParamLike, AudioState, Channel, ChannelName, GainNodeLike, PCMBufferLike, PlaySFXOptions, SFXHandle, SynthEnvelope, SynthSound, SynthWaveform };
159
211
  //# sourceMappingURL=index.d.ts.map
@@ -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"],"mappings":";;;;UAKiB;WACN;;UAGM;WACN,MAAM;EACf,QAAQ,MAAM,2BAA2B;EACzC;;UAGe;EACf;EACA,eAAe,eAAe;EAC9B,wBAAwB,eAAe;;UAGxB;WACN;WACA;WACA;WACA;;UAGM;EACf,QAAQ;EACR;;;;;WAKS;IAAiB;;EAC1B,QAAQ,MAAM,eAAe;EAC7B;EACA,MAAM;EACN,KAAK;EACL,WAAW,MAAM,2BAA2B;;UAG7B;WACN;WACA;WACA,aAAa;EACtB,cAAc;EACd,sBAAsB;EACtB,UAAU;EACV,WAAW;EACX,SAAS;;;KAIC;;;;;qBAMC;UACH;;MAGJ,SAAS;;MAMT,WAAW;;MAKX;;EAKJ,KAAK,eAAe;;EAMd,WAAW;;EAOX,UAAU;;EAOV,SAAS;;;UClGA;WACN;;EAET;;WAES,MAAM;;;KAIL;;;;;wBAMI,eAAe,KAAK,mBAAmB,IAAI,aAAa;;;;;qBCP3D;UACH;UACA;UACA;UACA;UACA;UACA;;MAGJ;;EAKJ,QAAQ,KAAK,kBAAkB,QAAQ;;EAMvC,SAAS,cAAc,QAAQ;;EAK/B,KAAK,cAAc;;EAgCnB;;;;;EAQA,YAAY,cAAc,kBAAkB;UA+CpC;;;UCxHO;;EAEf;;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;;EA+D3C"}
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"}
package/dist/index.js CHANGED
@@ -1,5 +1,10 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  // src/audio-manager.ts
3
+ /** Registers the end-of-playback handler on whichever accessor the node exposes. */
4
+ function setSourceEndHandler(source, handler) {
5
+ if ("onEnded" in source) source.onEnded = handler;
6
+ else source.onended = handler;
7
+ }
3
8
  /**
4
9
  * AudioManager — manages the AudioContext lifecycle.
5
10
  * Wraps react-native-audio-api's AudioContext.
@@ -106,25 +111,9 @@ var Music = class {
106
111
  const buffer = this.buffers.get(name);
107
112
  if (!buffer) return;
108
113
  this.stopInternal();
109
- const source = this.ctx.createBufferSource();
110
- source.buffer = buffer;
111
- source.loop = loop;
112
- const gain = this.ctx.createGain();
113
- gain.gain.value = 1;
114
- source.connect(gain);
115
- gain.connect(this.output);
116
- source.start();
117
- this.currentSource = source;
118
- this.currentGain = gain;
119
- this.currentName = name;
120
- source.onended = () => {
121
- if (this.currentSource === source) {
122
- this.currentSource = null;
123
- this.currentGain = null;
124
- this.currentName = null;
125
- }
126
- gain.disconnect();
127
- };
114
+ this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {
115
+ g.gain.value = 1;
116
+ });
128
117
  }
129
118
  /** Stop the current track. */
130
119
  stop() {
@@ -148,26 +137,31 @@ var Music = class {
148
137
  oldSource.stop(now + duration);
149
138
  } catch {}
150
139
  }
151
- const source = this.ctx.createBufferSource();
140
+ this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {
141
+ g.gain.setValueAtTime(0, now);
142
+ g.gain.linearRampToValueAtTime(1, now + duration);
143
+ });
144
+ }
145
+ startTrack(ctx, output, name, buffer, loop, prime) {
146
+ const source = ctx.createBufferSource();
152
147
  source.buffer = buffer;
153
148
  source.loop = loop;
154
- const gain = this.ctx.createGain();
155
- gain.gain.setValueAtTime(0, now);
156
- gain.gain.linearRampToValueAtTime(1, now + duration);
149
+ const gain = ctx.createGain();
150
+ prime(gain);
157
151
  source.connect(gain);
158
- gain.connect(this.output);
152
+ gain.connect(output);
159
153
  source.start();
160
154
  this.currentSource = source;
161
155
  this.currentGain = gain;
162
156
  this.currentName = name;
163
- source.onended = () => {
157
+ setSourceEndHandler(source, () => {
164
158
  if (this.currentSource === source) {
165
159
  this.currentSource = null;
166
160
  this.currentGain = null;
167
161
  this.currentName = null;
168
162
  }
169
163
  gain.disconnect();
170
- };
164
+ });
171
165
  }
172
166
  stopInternal() {
173
167
  if (this.currentSource) try {
@@ -243,12 +237,14 @@ var SFXPool = class {
243
237
  }
244
238
  };
245
239
  this.active.push(entry);
246
- source.onended = () => {
240
+ setSourceEndHandler(source, () => {
247
241
  const idx = this.active.indexOf(entry);
248
242
  if (idx !== -1) this.active.splice(idx, 1);
249
243
  gain.disconnect();
250
- };
251
- source.start();
244
+ });
245
+ const delay = opts?.delay;
246
+ if (delay !== void 0 && Number.isFinite(delay) && delay > 0) source.start(this.ctx.currentTime + delay);
247
+ else source.start();
252
248
  return { stop: () => {
253
249
  entry.stop();
254
250
  const idx = this.active.indexOf(entry);
@@ -261,9 +257,72 @@ var SFXPool = class {
261
257
  this.active.length = 0;
262
258
  }
263
259
  };
260
+ // src/synth.ts
261
+ const TWO_PI = Math.PI * 2;
262
+ /** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */
263
+ function synthSampleCount(duration, sampleRate) {
264
+ if (!Number.isFinite(duration) || duration < 0) return 0;
265
+ return Math.ceil(duration * sampleRate);
266
+ }
267
+ /**
268
+ * Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples
269
+ * written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.
270
+ */
271
+ function renderSynth(sound, sampleRate, out) {
272
+ if (!Number.isFinite(sampleRate) || sampleRate <= 0) return 0;
273
+ const duration = sound.duration;
274
+ const n = Math.min(out.length, synthSampleCount(duration, sampleRate));
275
+ const wave = sound.wave;
276
+ const volume = sound.volume ?? 1;
277
+ const f0 = sound.frequency;
278
+ const sweep = ((sound.endFrequency ?? f0) - f0) / duration;
279
+ const env = sound.envelope;
280
+ const attack = env ? env.attack : 0;
281
+ const decay = env ? env.decay : 0;
282
+ const sustain = env ? env.sustain : 1;
283
+ const release = env ? env.release : 0;
284
+ const decayEnd = attack + decay;
285
+ const releaseStart = duration - release;
286
+ const dt = 1 / sampleRate;
287
+ let phase = 0;
288
+ let rng = (sound.seed ?? 1) | 0 || 1;
289
+ for (let i = 0; i < n; i++) {
290
+ const t = i * dt;
291
+ let osc;
292
+ switch (wave) {
293
+ case "sine":
294
+ osc = Math.sin(TWO_PI * phase);
295
+ break;
296
+ case "square":
297
+ osc = phase < .5 ? 1 : -1;
298
+ break;
299
+ case "saw":
300
+ osc = 2 * phase - 1;
301
+ break;
302
+ default:
303
+ rng ^= rng << 13;
304
+ rng ^= rng >>> 17;
305
+ rng ^= rng << 5;
306
+ osc = (rng >>> 0) / 2147483648 - 1;
307
+ }
308
+ let gain = t < attack ? t / attack : t < decayEnd ? 1 - (1 - sustain) * (t - attack) / decay : sustain;
309
+ if (release > 0 && t >= releaseStart) gain *= (duration - t) / release;
310
+ out[i] = osc * gain * volume;
311
+ phase += (f0 + sweep * t) * dt;
312
+ if (phase >= 1) phase -= Math.floor(phase);
313
+ }
314
+ return n;
315
+ }
316
+ /** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */
317
+ function fillPCMBuffer(buffer, pcm) {
318
+ for (let c = 0; c < buffer.numberOfChannels; c++) buffer.copyToChannel(pcm, c);
319
+ }
264
320
  exports.AudioManager = AudioManager;
265
321
  exports.Music = Music;
266
322
  exports.SFXPool = SFXPool;
267
323
  exports.createChannels = createChannels;
324
+ exports.fillPCMBuffer = fillPCMBuffer;
325
+ exports.renderSynth = renderSynth;
326
+ exports.synthSampleCount = synthSampleCount;
268
327
 
269
328
  //# sourceMappingURL=index.js.map
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"],"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\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\nexport interface AudioContextLike {\n readonly state: 'suspended' | 'running' | 'closed';\n readonly currentTime: number;\n readonly destination: AudioDestinationNodeLike;\n createGain(): GainNodeLike;\n createBufferSource(): AudioBufferSourceNodeLike;\n resume(): Promise<void>;\n suspend(): Promise<void>;\n close(): Promise<void>;\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';\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 const source = this.ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = loop;\n\n const gain = this.ctx.createGain();\n gain.gain.value = 1;\n source.connect(gain);\n gain.connect(this.output);\n\n source.start();\n this.currentSource = source;\n this.currentGain = gain;\n this.currentName = name;\n\n source.onended = () => {\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 /** 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 const source = this.ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = loop;\n\n const gain = this.ctx.createGain();\n gain.gain.setValueAtTime(0, now);\n gain.gain.linearRampToValueAtTime(1, now + duration);\n source.connect(gain);\n gain.connect(this.output);\n\n source.start();\n this.currentSource = source;\n this.currentGain = gain;\n this.currentName = name;\n\n source.onended = () => {\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';\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}\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 source.onended = () => {\n const idx = this.active.indexOf(entry);\n if (idx !== -1) {\n this.active.splice(idx, 1);\n }\n gain.disconnect();\n };\n\n source.start();\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"],"mappings":";;;;;;AA6DA,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,MA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AAY,OAAO;EACzB,IAAI,aAAa,MAAM,SAAS,KAAA,GAC9B,UAAU,QAAQ,KAAK;EAIzB,MAAM,OAAO,KAAK,IAAI,WAAW;EACjC,KAAK,KAAK,QAAQ,MAAM,UAAU;EAClC,OAAO,QAAQ,IAAI;EACnB,KAAK,QAAQ,KAAK,MAAM;EAExB,MAAM,QAAsB;GAC1B;GACA,OAAO;IACL,IAAI;KACF,OAAO,KAAK;IACd,QAAQ,CAER;IACA,KAAK,WAAW;GAClB;EACF;EAEA,KAAK,OAAO,KAAK,KAAK;EAGtB,OAAO,gBAAgB;GACrB,MAAM,MAAM,KAAK,OAAO,QAAQ,KAAK;GACrC,IAAI,QAAQ,IACV,KAAK,OAAO,OAAO,KAAK,CAAC;GAE3B,KAAK,WAAW;EAClB;EAEA,OAAO,MAAM;EAEb,OAAO,EACL,YAAY;GACV,MAAM,KAAK;GACX,MAAM,MAAM,KAAK,OAAO,QAAQ,KAAK;GACrC,IAAI,QAAQ,IACV,KAAK,OAAO,OAAO,KAAK,CAAC;EAE7B,EACF;CACF;;CAGA,UAAgB;EACd,KAAK,MAAM,SAAS,KAAK,QACvB,MAAM,KAAK;EAEb,KAAK,OAAO,SAAS;CACvB;AACF"}
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;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,MA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BAAkB,KAAK,OAAO,cAAc,KAAK,CAAC;AAC/E"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,9 @@
1
1
  // src/audio-manager.ts
2
+ /** Registers the end-of-playback handler on whichever accessor the node exposes. */
3
+ function setSourceEndHandler(source, handler) {
4
+ if ("onEnded" in source) source.onEnded = handler;
5
+ else source.onended = handler;
6
+ }
2
7
  /**
3
8
  * AudioManager — manages the AudioContext lifecycle.
4
9
  * Wraps react-native-audio-api's AudioContext.
@@ -105,25 +110,9 @@ var Music = class {
105
110
  const buffer = this.buffers.get(name);
106
111
  if (!buffer) return;
107
112
  this.stopInternal();
108
- const source = this.ctx.createBufferSource();
109
- source.buffer = buffer;
110
- source.loop = loop;
111
- const gain = this.ctx.createGain();
112
- gain.gain.value = 1;
113
- source.connect(gain);
114
- gain.connect(this.output);
115
- source.start();
116
- this.currentSource = source;
117
- this.currentGain = gain;
118
- this.currentName = name;
119
- source.onended = () => {
120
- if (this.currentSource === source) {
121
- this.currentSource = null;
122
- this.currentGain = null;
123
- this.currentName = null;
124
- }
125
- gain.disconnect();
126
- };
113
+ this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {
114
+ g.gain.value = 1;
115
+ });
127
116
  }
128
117
  /** Stop the current track. */
129
118
  stop() {
@@ -147,26 +136,31 @@ var Music = class {
147
136
  oldSource.stop(now + duration);
148
137
  } catch {}
149
138
  }
150
- const source = this.ctx.createBufferSource();
139
+ this.startTrack(this.ctx, this.output, name, buffer, loop, (g) => {
140
+ g.gain.setValueAtTime(0, now);
141
+ g.gain.linearRampToValueAtTime(1, now + duration);
142
+ });
143
+ }
144
+ startTrack(ctx, output, name, buffer, loop, prime) {
145
+ const source = ctx.createBufferSource();
151
146
  source.buffer = buffer;
152
147
  source.loop = loop;
153
- const gain = this.ctx.createGain();
154
- gain.gain.setValueAtTime(0, now);
155
- gain.gain.linearRampToValueAtTime(1, now + duration);
148
+ const gain = ctx.createGain();
149
+ prime(gain);
156
150
  source.connect(gain);
157
- gain.connect(this.output);
151
+ gain.connect(output);
158
152
  source.start();
159
153
  this.currentSource = source;
160
154
  this.currentGain = gain;
161
155
  this.currentName = name;
162
- source.onended = () => {
156
+ setSourceEndHandler(source, () => {
163
157
  if (this.currentSource === source) {
164
158
  this.currentSource = null;
165
159
  this.currentGain = null;
166
160
  this.currentName = null;
167
161
  }
168
162
  gain.disconnect();
169
- };
163
+ });
170
164
  }
171
165
  stopInternal() {
172
166
  if (this.currentSource) try {
@@ -242,12 +236,14 @@ var SFXPool = class {
242
236
  }
243
237
  };
244
238
  this.active.push(entry);
245
- source.onended = () => {
239
+ setSourceEndHandler(source, () => {
246
240
  const idx = this.active.indexOf(entry);
247
241
  if (idx !== -1) this.active.splice(idx, 1);
248
242
  gain.disconnect();
249
- };
250
- source.start();
243
+ });
244
+ const delay = opts?.delay;
245
+ if (delay !== void 0 && Number.isFinite(delay) && delay > 0) source.start(this.ctx.currentTime + delay);
246
+ else source.start();
251
247
  return { stop: () => {
252
248
  entry.stop();
253
249
  const idx = this.active.indexOf(entry);
@@ -260,6 +256,66 @@ var SFXPool = class {
260
256
  this.active.length = 0;
261
257
  }
262
258
  };
263
- export { AudioManager, Music, SFXPool, createChannels };
259
+ // src/synth.ts
260
+ const TWO_PI = Math.PI * 2;
261
+ /** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */
262
+ function synthSampleCount(duration, sampleRate) {
263
+ if (!Number.isFinite(duration) || duration < 0) return 0;
264
+ return Math.ceil(duration * sampleRate);
265
+ }
266
+ /**
267
+ * Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples
268
+ * written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.
269
+ */
270
+ function renderSynth(sound, sampleRate, out) {
271
+ if (!Number.isFinite(sampleRate) || sampleRate <= 0) return 0;
272
+ const duration = sound.duration;
273
+ const n = Math.min(out.length, synthSampleCount(duration, sampleRate));
274
+ const wave = sound.wave;
275
+ const volume = sound.volume ?? 1;
276
+ const f0 = sound.frequency;
277
+ const sweep = ((sound.endFrequency ?? f0) - f0) / duration;
278
+ const env = sound.envelope;
279
+ const attack = env ? env.attack : 0;
280
+ const decay = env ? env.decay : 0;
281
+ const sustain = env ? env.sustain : 1;
282
+ const release = env ? env.release : 0;
283
+ const decayEnd = attack + decay;
284
+ const releaseStart = duration - release;
285
+ const dt = 1 / sampleRate;
286
+ let phase = 0;
287
+ let rng = (sound.seed ?? 1) | 0 || 1;
288
+ for (let i = 0; i < n; i++) {
289
+ const t = i * dt;
290
+ let osc;
291
+ switch (wave) {
292
+ case "sine":
293
+ osc = Math.sin(TWO_PI * phase);
294
+ break;
295
+ case "square":
296
+ osc = phase < .5 ? 1 : -1;
297
+ break;
298
+ case "saw":
299
+ osc = 2 * phase - 1;
300
+ break;
301
+ default:
302
+ rng ^= rng << 13;
303
+ rng ^= rng >>> 17;
304
+ rng ^= rng << 5;
305
+ osc = (rng >>> 0) / 2147483648 - 1;
306
+ }
307
+ let gain = t < attack ? t / attack : t < decayEnd ? 1 - (1 - sustain) * (t - attack) / decay : sustain;
308
+ if (release > 0 && t >= releaseStart) gain *= (duration - t) / release;
309
+ out[i] = osc * gain * volume;
310
+ phase += (f0 + sweep * t) * dt;
311
+ if (phase >= 1) phase -= Math.floor(phase);
312
+ }
313
+ return n;
314
+ }
315
+ /** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */
316
+ function fillPCMBuffer(buffer, pcm) {
317
+ for (let c = 0; c < buffer.numberOfChannels; c++) buffer.copyToChannel(pcm, c);
318
+ }
319
+ export { AudioManager, Music, SFXPool, createChannels, fillPCMBuffer, renderSynth, synthSampleCount };
264
320
 
265
321
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/audio-manager.ts","../src/channels.ts","../src/music.ts","../src/sfx-pool.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\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\nexport interface AudioContextLike {\n readonly state: 'suspended' | 'running' | 'closed';\n readonly currentTime: number;\n readonly destination: AudioDestinationNodeLike;\n createGain(): GainNodeLike;\n createBufferSource(): AudioBufferSourceNodeLike;\n resume(): Promise<void>;\n suspend(): Promise<void>;\n close(): Promise<void>;\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';\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 const source = this.ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = loop;\n\n const gain = this.ctx.createGain();\n gain.gain.value = 1;\n source.connect(gain);\n gain.connect(this.output);\n\n source.start();\n this.currentSource = source;\n this.currentGain = gain;\n this.currentName = name;\n\n source.onended = () => {\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 /** 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 const source = this.ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = loop;\n\n const gain = this.ctx.createGain();\n gain.gain.setValueAtTime(0, now);\n gain.gain.linearRampToValueAtTime(1, now + duration);\n source.connect(gain);\n gain.connect(this.output);\n\n source.start();\n this.currentSource = source;\n this.currentGain = gain;\n this.currentName = name;\n\n source.onended = () => {\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';\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}\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 source.onended = () => {\n const idx = this.active.indexOf(entry);\n if (idx !== -1) {\n this.active.splice(idx, 1);\n }\n gain.disconnect();\n };\n\n source.start();\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"],"mappings":";;;;;AA6DA,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;E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I,cAAsB;EACxB,OAAO,KAAK,OAAO;CACrB;;CAGA,KAAK,MAAc,MAAyC;EAC1D,MAAM,SAAS,KAAK,QAAQ,IAAI,IAAI;EACpC,IAAI,CAAC,UAAU,CAAC,KAAK,OAAO,CAAC,KAAK,QAAQ,OAAO;EAGjD,OAAO,KAAK,OAAO,UAAU,KAAK,cAEhC,KADoB,OAAO,MACtB,CAAC,EAAE,KAAK;EAGf,MAAM,SAAS,KAAK,IAAI,mBAAmB;EAC3C,OAAO,SAAS;EAChB,OAAO,OAAO,MAAM,QAAQ;EAG5B,MAAM,YAAY,OAAO;EACzB,IAAI,aAAa,MAAM,SAAS,KAAA,GAC9B,UAAU,QAAQ,KAAK;EAIzB,MAAM,OAAO,KAAK,IAAI,WAAW;EACjC,KAAK,KAAK,QAAQ,MAAM,UAAU;EAClC,OAAO,QAAQ,IAAI;EACnB,KAAK,QAAQ,KAAK,MAAM;EAExB,MAAM,QAAsB;GAC1B;GACA,OAAO;IACL,IAAI;KACF,OAAO,KAAK;IACd,QAAQ,CAER;IACA,KAAK,WAAW;GAClB;EACF;EAEA,KAAK,OAAO,KAAK,KAAK;EAGtB,OAAO,gBAAgB;GACrB,MAAM,MAAM,KAAK,OAAO,QAAQ,KAAK;GACrC,IAAI,QAAQ,IACV,KAAK,OAAO,OAAO,KAAK,CAAC;GAE3B,KAAK,WAAW;EAClB;EAEA,OAAO,MAAM;EAEb,OAAO,EACL,YAAY;GACV,MAAM,KAAK;GACX,MAAM,MAAM,KAAK,OAAO,QAAQ,KAAK;GACrC,IAAI,QAAQ,IACV,KAAK,OAAO,OAAO,KAAK,CAAC;EAE7B,EACF;CACF;;CAGA,UAAgB;EACd,KAAK,MAAM,SAAS,KAAK,QACvB,MAAM,KAAK;EAEb,KAAK,OAAO,SAAS;CACvB;AACF"}
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,O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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,8 +1,8 @@
1
1
  {
2
2
  "name": "@flare-engine/audio",
3
- "version": "0.4.8",
3
+ "version": "0.4.11",
4
4
  "description": "AudioManager, SFX pool, music crossfade",
5
- "keywords": ["flare-engine", "audio", "sfx", "music"],
5
+ "keywords": ["flare-engine", "audio", "sfx", "music", "react-native", "typescript"],
6
6
  "license": "Apache-2.0",
7
7
  "author": "Grzegorz Otto",
8
8
  "homepage": "https://github.com/grzott/flare-engine#readme",