@flare-engine/audio 0.4.7 → 0.4.10
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 +24 -1
- package/dist/index.d.mts +52 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +52 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +77 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +75 -8
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
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>;
|
|
@@ -121,6 +135,8 @@ interface PlaySFXOptions {
|
|
|
121
135
|
rate?: number;
|
|
122
136
|
/** Whether to loop. Default: false. */
|
|
123
137
|
loop?: boolean;
|
|
138
|
+
/** Seconds to wait before starting, on the context clock. Default: 0 (start at once). Non-finite or non-positive values start at once. */
|
|
139
|
+
delay?: number;
|
|
124
140
|
}
|
|
125
141
|
/** A handle to a playing SFX instance. */
|
|
126
142
|
interface SFXHandle {
|
|
@@ -155,5 +171,40 @@ export declare class SFXPool {
|
|
|
155
171
|
/** Stop all active sounds. */
|
|
156
172
|
stopAll(): void;
|
|
157
173
|
}
|
|
158
|
-
|
|
174
|
+
type SynthWaveform = 'sine' | 'square' | 'saw' | 'noise';
|
|
175
|
+
interface SynthEnvelope {
|
|
176
|
+
/** Seconds from silence to full level. */
|
|
177
|
+
attack: number;
|
|
178
|
+
/** Seconds from full level down to `sustain`. */
|
|
179
|
+
decay: number;
|
|
180
|
+
/** Level (0–1) held after the decay until the release starts. */
|
|
181
|
+
sustain: number;
|
|
182
|
+
/** Seconds of fade to silence, counted back from the end of the sound. */
|
|
183
|
+
release: number;
|
|
184
|
+
}
|
|
185
|
+
interface SynthSound {
|
|
186
|
+
wave: SynthWaveform;
|
|
187
|
+
/** Hz at the start. Ignored by `noise`. */
|
|
188
|
+
frequency: number;
|
|
189
|
+
/** Hz at the end, reached by a linear sweep from `frequency`. Default: `frequency` (no sweep). */
|
|
190
|
+
endFrequency?: number;
|
|
191
|
+
/** Seconds. */
|
|
192
|
+
duration: number;
|
|
193
|
+
/** Default: `{ attack: 0, decay: 0, sustain: 1, release: 0 }` (flat). */
|
|
194
|
+
envelope?: SynthEnvelope;
|
|
195
|
+
/** Peak amplitude (0–1). Default 1. */
|
|
196
|
+
volume?: number;
|
|
197
|
+
/** 32-bit seed for `noise`; the same seed renders the same samples. Default 1. */
|
|
198
|
+
seed?: number;
|
|
199
|
+
}
|
|
200
|
+
/** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */
|
|
201
|
+
export declare function synthSampleCount(duration: number, sampleRate: number): number;
|
|
202
|
+
/**
|
|
203
|
+
* Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples
|
|
204
|
+
* written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.
|
|
205
|
+
*/
|
|
206
|
+
export declare function renderSynth(sound: SynthSound, sampleRate: number, out: Float32Array): number;
|
|
207
|
+
/** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */
|
|
208
|
+
export declare function fillPCMBuffer(buffer: PCMBufferLike, pcm: Float32Array): void;
|
|
209
|
+
export type { AudioBufferLike, AudioBufferSourceNodeLike, AudioContextLike, AudioDestinationNodeLike, AudioParamLike, AudioState, Channel, ChannelName, GainNodeLike, PCMBufferLike, PlaySFXOptions, SFXHandle, SynthEnvelope, SynthSound, SynthWaveform };
|
|
159
210
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -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;;
|
|
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;;EAgCnB;;;;;EAQA,YAAY,cAAc,kBAAkB;UA+CpC;;;UCxHO;;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>;
|
|
@@ -121,6 +135,8 @@ interface PlaySFXOptions {
|
|
|
121
135
|
rate?: number;
|
|
122
136
|
/** Whether to loop. Default: false. */
|
|
123
137
|
loop?: boolean;
|
|
138
|
+
/** Seconds to wait before starting, on the context clock. Default: 0 (start at once). Non-finite or non-positive values start at once. */
|
|
139
|
+
delay?: number;
|
|
124
140
|
}
|
|
125
141
|
/** A handle to a playing SFX instance. */
|
|
126
142
|
interface SFXHandle {
|
|
@@ -155,5 +171,40 @@ export declare class SFXPool {
|
|
|
155
171
|
/** Stop all active sounds. */
|
|
156
172
|
stopAll(): void;
|
|
157
173
|
}
|
|
158
|
-
|
|
174
|
+
type SynthWaveform = 'sine' | 'square' | 'saw' | 'noise';
|
|
175
|
+
interface SynthEnvelope {
|
|
176
|
+
/** Seconds from silence to full level. */
|
|
177
|
+
attack: number;
|
|
178
|
+
/** Seconds from full level down to `sustain`. */
|
|
179
|
+
decay: number;
|
|
180
|
+
/** Level (0–1) held after the decay until the release starts. */
|
|
181
|
+
sustain: number;
|
|
182
|
+
/** Seconds of fade to silence, counted back from the end of the sound. */
|
|
183
|
+
release: number;
|
|
184
|
+
}
|
|
185
|
+
interface SynthSound {
|
|
186
|
+
wave: SynthWaveform;
|
|
187
|
+
/** Hz at the start. Ignored by `noise`. */
|
|
188
|
+
frequency: number;
|
|
189
|
+
/** Hz at the end, reached by a linear sweep from `frequency`. Default: `frequency` (no sweep). */
|
|
190
|
+
endFrequency?: number;
|
|
191
|
+
/** Seconds. */
|
|
192
|
+
duration: number;
|
|
193
|
+
/** Default: `{ attack: 0, decay: 0, sustain: 1, release: 0 }` (flat). */
|
|
194
|
+
envelope?: SynthEnvelope;
|
|
195
|
+
/** Peak amplitude (0–1). Default 1. */
|
|
196
|
+
volume?: number;
|
|
197
|
+
/** 32-bit seed for `noise`; the same seed renders the same samples. Default 1. */
|
|
198
|
+
seed?: number;
|
|
199
|
+
}
|
|
200
|
+
/** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */
|
|
201
|
+
export declare function synthSampleCount(duration: number, sampleRate: number): number;
|
|
202
|
+
/**
|
|
203
|
+
* Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples
|
|
204
|
+
* written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.
|
|
205
|
+
*/
|
|
206
|
+
export declare function renderSynth(sound: SynthSound, sampleRate: number, out: Float32Array): number;
|
|
207
|
+
/** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */
|
|
208
|
+
export declare function fillPCMBuffer(buffer: PCMBufferLike, pcm: Float32Array): void;
|
|
209
|
+
export type { AudioBufferLike, AudioBufferSourceNodeLike, AudioContextLike, AudioDestinationNodeLike, AudioParamLike, AudioState, Channel, ChannelName, GainNodeLike, PCMBufferLike, PlaySFXOptions, SFXHandle, SynthEnvelope, SynthSound, SynthWaveform };
|
|
159
210
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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;;
|
|
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;;EAgCnB;;;;;EAQA,YAAY,cAAc,kBAAkB;UA+CpC;;;UCxHO;;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.
|
|
@@ -117,14 +122,14 @@ var Music = class {
|
|
|
117
122
|
this.currentSource = source;
|
|
118
123
|
this.currentGain = gain;
|
|
119
124
|
this.currentName = name;
|
|
120
|
-
source
|
|
125
|
+
setSourceEndHandler(source, () => {
|
|
121
126
|
if (this.currentSource === source) {
|
|
122
127
|
this.currentSource = null;
|
|
123
128
|
this.currentGain = null;
|
|
124
129
|
this.currentName = null;
|
|
125
130
|
}
|
|
126
131
|
gain.disconnect();
|
|
127
|
-
};
|
|
132
|
+
});
|
|
128
133
|
}
|
|
129
134
|
/** Stop the current track. */
|
|
130
135
|
stop() {
|
|
@@ -160,14 +165,14 @@ var Music = class {
|
|
|
160
165
|
this.currentSource = source;
|
|
161
166
|
this.currentGain = gain;
|
|
162
167
|
this.currentName = name;
|
|
163
|
-
source
|
|
168
|
+
setSourceEndHandler(source, () => {
|
|
164
169
|
if (this.currentSource === source) {
|
|
165
170
|
this.currentSource = null;
|
|
166
171
|
this.currentGain = null;
|
|
167
172
|
this.currentName = null;
|
|
168
173
|
}
|
|
169
174
|
gain.disconnect();
|
|
170
|
-
};
|
|
175
|
+
});
|
|
171
176
|
}
|
|
172
177
|
stopInternal() {
|
|
173
178
|
if (this.currentSource) try {
|
|
@@ -243,12 +248,14 @@ var SFXPool = class {
|
|
|
243
248
|
}
|
|
244
249
|
};
|
|
245
250
|
this.active.push(entry);
|
|
246
|
-
source
|
|
251
|
+
setSourceEndHandler(source, () => {
|
|
247
252
|
const idx = this.active.indexOf(entry);
|
|
248
253
|
if (idx !== -1) this.active.splice(idx, 1);
|
|
249
254
|
gain.disconnect();
|
|
250
|
-
};
|
|
251
|
-
|
|
255
|
+
});
|
|
256
|
+
const delay = opts?.delay;
|
|
257
|
+
if (delay !== void 0 && Number.isFinite(delay) && delay > 0) source.start(this.ctx.currentTime + delay);
|
|
258
|
+
else source.start();
|
|
252
259
|
return { stop: () => {
|
|
253
260
|
entry.stop();
|
|
254
261
|
const idx = this.active.indexOf(entry);
|
|
@@ -261,9 +268,72 @@ var SFXPool = class {
|
|
|
261
268
|
this.active.length = 0;
|
|
262
269
|
}
|
|
263
270
|
};
|
|
271
|
+
// src/synth.ts
|
|
272
|
+
const TWO_PI = Math.PI * 2;
|
|
273
|
+
/** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */
|
|
274
|
+
function synthSampleCount(duration, sampleRate) {
|
|
275
|
+
if (!Number.isFinite(duration) || duration < 0) return 0;
|
|
276
|
+
return Math.ceil(duration * sampleRate);
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples
|
|
280
|
+
* written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.
|
|
281
|
+
*/
|
|
282
|
+
function renderSynth(sound, sampleRate, out) {
|
|
283
|
+
if (!Number.isFinite(sampleRate) || sampleRate <= 0) return 0;
|
|
284
|
+
const duration = sound.duration;
|
|
285
|
+
const n = Math.min(out.length, synthSampleCount(duration, sampleRate));
|
|
286
|
+
const wave = sound.wave;
|
|
287
|
+
const volume = sound.volume ?? 1;
|
|
288
|
+
const f0 = sound.frequency;
|
|
289
|
+
const sweep = ((sound.endFrequency ?? f0) - f0) / duration;
|
|
290
|
+
const env = sound.envelope;
|
|
291
|
+
const attack = env ? env.attack : 0;
|
|
292
|
+
const decay = env ? env.decay : 0;
|
|
293
|
+
const sustain = env ? env.sustain : 1;
|
|
294
|
+
const release = env ? env.release : 0;
|
|
295
|
+
const decayEnd = attack + decay;
|
|
296
|
+
const releaseStart = duration - release;
|
|
297
|
+
const dt = 1 / sampleRate;
|
|
298
|
+
let phase = 0;
|
|
299
|
+
let rng = (sound.seed ?? 1) | 0 || 1;
|
|
300
|
+
for (let i = 0; i < n; i++) {
|
|
301
|
+
const t = i * dt;
|
|
302
|
+
let osc;
|
|
303
|
+
switch (wave) {
|
|
304
|
+
case "sine":
|
|
305
|
+
osc = Math.sin(TWO_PI * phase);
|
|
306
|
+
break;
|
|
307
|
+
case "square":
|
|
308
|
+
osc = phase < .5 ? 1 : -1;
|
|
309
|
+
break;
|
|
310
|
+
case "saw":
|
|
311
|
+
osc = 2 * phase - 1;
|
|
312
|
+
break;
|
|
313
|
+
default:
|
|
314
|
+
rng ^= rng << 13;
|
|
315
|
+
rng ^= rng >>> 17;
|
|
316
|
+
rng ^= rng << 5;
|
|
317
|
+
osc = (rng >>> 0) / 2147483648 - 1;
|
|
318
|
+
}
|
|
319
|
+
let gain = t < attack ? t / attack : t < decayEnd ? 1 - (1 - sustain) * (t - attack) / decay : sustain;
|
|
320
|
+
if (release > 0 && t >= releaseStart) gain *= (duration - t) / release;
|
|
321
|
+
out[i] = osc * gain * volume;
|
|
322
|
+
phase += (f0 + sweep * t) * dt;
|
|
323
|
+
if (phase >= 1) phase -= Math.floor(phase);
|
|
324
|
+
}
|
|
325
|
+
return n;
|
|
326
|
+
}
|
|
327
|
+
/** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */
|
|
328
|
+
function fillPCMBuffer(buffer, pcm) {
|
|
329
|
+
for (let c = 0; c < buffer.numberOfChannels; c++) buffer.copyToChannel(pcm, c);
|
|
330
|
+
}
|
|
264
331
|
exports.AudioManager = AudioManager;
|
|
265
332
|
exports.Music = Music;
|
|
266
333
|
exports.SFXPool = SFXPool;
|
|
267
334
|
exports.createChannels = createChannels;
|
|
335
|
+
exports.fillPCMBuffer = fillPCMBuffer;
|
|
336
|
+
exports.renderSynth = renderSynth;
|
|
337
|
+
exports.synthSampleCount = synthSampleCount;
|
|
268
338
|
|
|
269
339
|
//# 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,MAAM;GACrB,KAAK,MAAM;EACb;CACF;AACF;;;;;;ACzFA,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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,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 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 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 /** 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 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;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
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.
|
|
@@ -116,14 +121,14 @@ var Music = class {
|
|
|
116
121
|
this.currentSource = source;
|
|
117
122
|
this.currentGain = gain;
|
|
118
123
|
this.currentName = name;
|
|
119
|
-
source
|
|
124
|
+
setSourceEndHandler(source, () => {
|
|
120
125
|
if (this.currentSource === source) {
|
|
121
126
|
this.currentSource = null;
|
|
122
127
|
this.currentGain = null;
|
|
123
128
|
this.currentName = null;
|
|
124
129
|
}
|
|
125
130
|
gain.disconnect();
|
|
126
|
-
};
|
|
131
|
+
});
|
|
127
132
|
}
|
|
128
133
|
/** Stop the current track. */
|
|
129
134
|
stop() {
|
|
@@ -159,14 +164,14 @@ var Music = class {
|
|
|
159
164
|
this.currentSource = source;
|
|
160
165
|
this.currentGain = gain;
|
|
161
166
|
this.currentName = name;
|
|
162
|
-
source
|
|
167
|
+
setSourceEndHandler(source, () => {
|
|
163
168
|
if (this.currentSource === source) {
|
|
164
169
|
this.currentSource = null;
|
|
165
170
|
this.currentGain = null;
|
|
166
171
|
this.currentName = null;
|
|
167
172
|
}
|
|
168
173
|
gain.disconnect();
|
|
169
|
-
};
|
|
174
|
+
});
|
|
170
175
|
}
|
|
171
176
|
stopInternal() {
|
|
172
177
|
if (this.currentSource) try {
|
|
@@ -242,12 +247,14 @@ var SFXPool = class {
|
|
|
242
247
|
}
|
|
243
248
|
};
|
|
244
249
|
this.active.push(entry);
|
|
245
|
-
source
|
|
250
|
+
setSourceEndHandler(source, () => {
|
|
246
251
|
const idx = this.active.indexOf(entry);
|
|
247
252
|
if (idx !== -1) this.active.splice(idx, 1);
|
|
248
253
|
gain.disconnect();
|
|
249
|
-
};
|
|
250
|
-
|
|
254
|
+
});
|
|
255
|
+
const delay = opts?.delay;
|
|
256
|
+
if (delay !== void 0 && Number.isFinite(delay) && delay > 0) source.start(this.ctx.currentTime + delay);
|
|
257
|
+
else source.start();
|
|
251
258
|
return { stop: () => {
|
|
252
259
|
entry.stop();
|
|
253
260
|
const idx = this.active.indexOf(entry);
|
|
@@ -260,6 +267,66 @@ var SFXPool = class {
|
|
|
260
267
|
this.active.length = 0;
|
|
261
268
|
}
|
|
262
269
|
};
|
|
263
|
-
|
|
270
|
+
// src/synth.ts
|
|
271
|
+
const TWO_PI = Math.PI * 2;
|
|
272
|
+
/** Samples `duration` seconds occupy at `sampleRate`: `ceil(duration * sampleRate)`, 0 for a non-finite or negative duration. */
|
|
273
|
+
function synthSampleCount(duration, sampleRate) {
|
|
274
|
+
if (!Number.isFinite(duration) || duration < 0) return 0;
|
|
275
|
+
return Math.ceil(duration * sampleRate);
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Renders `sound` as mono PCM in [-1, 1] into `out` from index 0 and returns the number of samples
|
|
279
|
+
* written: `min(out.length, synthSampleCount(sound.duration, sampleRate))`. Allocates nothing.
|
|
280
|
+
*/
|
|
281
|
+
function renderSynth(sound, sampleRate, out) {
|
|
282
|
+
if (!Number.isFinite(sampleRate) || sampleRate <= 0) return 0;
|
|
283
|
+
const duration = sound.duration;
|
|
284
|
+
const n = Math.min(out.length, synthSampleCount(duration, sampleRate));
|
|
285
|
+
const wave = sound.wave;
|
|
286
|
+
const volume = sound.volume ?? 1;
|
|
287
|
+
const f0 = sound.frequency;
|
|
288
|
+
const sweep = ((sound.endFrequency ?? f0) - f0) / duration;
|
|
289
|
+
const env = sound.envelope;
|
|
290
|
+
const attack = env ? env.attack : 0;
|
|
291
|
+
const decay = env ? env.decay : 0;
|
|
292
|
+
const sustain = env ? env.sustain : 1;
|
|
293
|
+
const release = env ? env.release : 0;
|
|
294
|
+
const decayEnd = attack + decay;
|
|
295
|
+
const releaseStart = duration - release;
|
|
296
|
+
const dt = 1 / sampleRate;
|
|
297
|
+
let phase = 0;
|
|
298
|
+
let rng = (sound.seed ?? 1) | 0 || 1;
|
|
299
|
+
for (let i = 0; i < n; i++) {
|
|
300
|
+
const t = i * dt;
|
|
301
|
+
let osc;
|
|
302
|
+
switch (wave) {
|
|
303
|
+
case "sine":
|
|
304
|
+
osc = Math.sin(TWO_PI * phase);
|
|
305
|
+
break;
|
|
306
|
+
case "square":
|
|
307
|
+
osc = phase < .5 ? 1 : -1;
|
|
308
|
+
break;
|
|
309
|
+
case "saw":
|
|
310
|
+
osc = 2 * phase - 1;
|
|
311
|
+
break;
|
|
312
|
+
default:
|
|
313
|
+
rng ^= rng << 13;
|
|
314
|
+
rng ^= rng >>> 17;
|
|
315
|
+
rng ^= rng << 5;
|
|
316
|
+
osc = (rng >>> 0) / 2147483648 - 1;
|
|
317
|
+
}
|
|
318
|
+
let gain = t < attack ? t / attack : t < decayEnd ? 1 - (1 - sustain) * (t - attack) / decay : sustain;
|
|
319
|
+
if (release > 0 && t >= releaseStart) gain *= (duration - t) / release;
|
|
320
|
+
out[i] = osc * gain * volume;
|
|
321
|
+
phase += (f0 + sweep * t) * dt;
|
|
322
|
+
if (phase >= 1) phase -= Math.floor(phase);
|
|
323
|
+
}
|
|
324
|
+
return n;
|
|
325
|
+
}
|
|
326
|
+
/** Copies `pcm` into every channel of `buffer` (a mono render fills a stereo buffer on both sides). */
|
|
327
|
+
function fillPCMBuffer(buffer, pcm) {
|
|
328
|
+
for (let c = 0; c < buffer.numberOfChannels; c++) buffer.copyToChannel(pcm, c);
|
|
329
|
+
}
|
|
330
|
+
export { AudioManager, Music, SFXPool, createChannels, fillPCMBuffer, renderSynth, synthSampleCount };
|
|
264
331
|
|
|
265
332
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -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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b,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 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 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 /** 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 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). */\n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AQ;CACZ,IAAI,OAAO,MAAM,QAAQ,KAAK,KAAK;CAEnC,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"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flare-engine/audio",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.10",
|
|
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",
|