@affectively/entrainment-audio 1.0.0

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.
@@ -0,0 +1,589 @@
1
+ /**
2
+ * Entrainment Audio Types
3
+ *
4
+ * TypeScript interfaces and types for brainwave entrainment system
5
+ */
6
+ /**
7
+ * Brainwave frequency bands based on EEG classification
8
+ */
9
+ type BrainwaveBand = 'delta' | 'theta' | 'alpha' | 'low-beta' | 'mid-beta' | 'high-beta' | 'gamma';
10
+ /**
11
+ * Generator types available in the entrainment engine
12
+ */
13
+ type GeneratorType = 'binaural' | 'isochronic' | 'monaural' | 'brown-noise' | 'pink-noise';
14
+ /**
15
+ * Playback state
16
+ */
17
+ type PlaybackState = 'stopped' | 'playing' | 'paused';
18
+ /**
19
+ * Brainwave preset configuration
20
+ */
21
+ interface BrainwavePreset {
22
+ id: BrainwaveBand;
23
+ name: string;
24
+ description: string;
25
+ frequencyRange: {
26
+ min: number;
27
+ max: number;
28
+ };
29
+ targetFrequency: number;
30
+ carrierFrequency: number;
31
+ color: string;
32
+ useCase: string;
33
+ }
34
+ /**
35
+ * Generator configuration
36
+ */
37
+ interface GeneratorConfig {
38
+ enabled: boolean;
39
+ volume: number;
40
+ type: GeneratorType;
41
+ }
42
+ /**
43
+ * Binaural generator configuration
44
+ */
45
+ interface BinauralConfig extends GeneratorConfig {
46
+ type: 'binaural';
47
+ carrierFrequency: number;
48
+ beatFrequency: number;
49
+ }
50
+ /**
51
+ * Isochronic generator configuration
52
+ */
53
+ interface IsochronicConfig extends GeneratorConfig {
54
+ type: 'isochronic';
55
+ carrierFrequency: number;
56
+ beatFrequency: number;
57
+ dutyCycle: number;
58
+ attackTime: number;
59
+ releaseTime: number;
60
+ }
61
+ /**
62
+ * Monaural generator configuration
63
+ */
64
+ interface MonauralConfig extends GeneratorConfig {
65
+ type: 'monaural';
66
+ frequency1: number;
67
+ frequency2: number;
68
+ beatFrequency: number;
69
+ }
70
+ /**
71
+ * Brown noise generator configuration
72
+ */
73
+ interface BrownNoiseConfig extends GeneratorConfig {
74
+ type: 'brown-noise';
75
+ filterStrength: number;
76
+ }
77
+ /**
78
+ * Pink noise generator configuration
79
+ */
80
+ interface PinkNoiseConfig extends GeneratorConfig {
81
+ type: 'pink-noise';
82
+ filterStrength: number;
83
+ }
84
+ /**
85
+ * Complete entrainment engine configuration
86
+ */
87
+ interface EntrainmentConfig {
88
+ preset?: BrainwaveBand;
89
+ manualMode: boolean;
90
+ manualCarrierFrequency?: number;
91
+ manualBeatFrequency?: number;
92
+ generators: {
93
+ binaural: BinauralConfig;
94
+ isochronic: IsochronicConfig;
95
+ monaural?: MonauralConfig;
96
+ brownNoise: BrownNoiseConfig;
97
+ pinkNoise?: PinkNoiseConfig;
98
+ };
99
+ masterVolume: number;
100
+ progressiveRamping: boolean;
101
+ rampingDuration: number;
102
+ mode: 'headphones' | 'speaker';
103
+ durationSeconds?: number;
104
+ }
105
+ /**
106
+ * Session information
107
+ */
108
+ interface SessionInfo {
109
+ startTime: number;
110
+ duration: number;
111
+ currentFrequency: number;
112
+ targetFrequency: number;
113
+ state: PlaybackState;
114
+ }
115
+ /**
116
+ * Safety warnings configuration
117
+ */
118
+ interface SafetyWarnings {
119
+ epilepsy: boolean;
120
+ driving: boolean;
121
+ pacemakers: boolean;
122
+ mentalHealth: boolean;
123
+ }
124
+ /**
125
+ * User settings for persistence
126
+ */
127
+ interface EntrainmentSettings {
128
+ lastPreset?: BrainwaveBand;
129
+ lastManualConfig?: {
130
+ carrierFrequency: number;
131
+ beatFrequency: number;
132
+ };
133
+ generatorStates: {
134
+ binaural: boolean;
135
+ isochronic: boolean;
136
+ monaural: boolean;
137
+ brownNoise: boolean;
138
+ };
139
+ volumeLevels: {
140
+ master: number;
141
+ binaural: number;
142
+ isochronic: number;
143
+ monaural: number;
144
+ brownNoise: number;
145
+ };
146
+ mode: 'headphones' | 'speaker';
147
+ progressiveRamping: boolean;
148
+ }
149
+
150
+ /**
151
+ * Brainwave State Presets
152
+ *
153
+ * Based on EEG frequency bands and scientific research on brainwave entrainment.
154
+ * Each preset defines carrier frequency, beat frequency, and recommended applications.
155
+ */
156
+
157
+ /**
158
+ * Delta (0.5-4 Hz): Deep sleep, unconsciousness, restoration
159
+ * Stage 3-4 NREM sleep. Below human hearing range, must use rhythmic modulation.
160
+ */
161
+ declare const DELTA_PRESET: BrainwavePreset;
162
+ /**
163
+ * Theta (4-8 Hz): Deep meditation, creativity, memory encoding
164
+ * Limbic system and hippocampal regions. Hypnagogic state.
165
+ */
166
+ declare const THETA_PRESET: BrainwavePreset;
167
+ /**
168
+ * Alpha (8-12 Hz): Relaxed alertness, "flow" state
169
+ * Visual cortex idling. Bridge between conscious and subconscious.
170
+ */
171
+ declare const ALPHA_PRESET: BrainwavePreset;
172
+ /**
173
+ * Low Beta / SMR (12-15 Hz): Calm focus, stillness
174
+ * Sensorimotor rhythm. Used in ADHD neurofeedback.
175
+ */
176
+ declare const LOW_BETA_PRESET: BrainwavePreset;
177
+ /**
178
+ * Mid Beta (15-20 Hz): Active focus, problem-solving
179
+ * Active cortical computation. Standard cognitive maintenance.
180
+ */
181
+ declare const MID_BETA_PRESET: BrainwavePreset;
182
+ /**
183
+ * High Beta (20-30 Hz): High energy, excitement
184
+ * Intense metabolic consumption. Can induce anxiety if prolonged.
185
+ */
186
+ declare const HIGH_BETA_PRESET: BrainwavePreset;
187
+ /**
188
+ * Gamma (30-100+ Hz): Peak performance, insight
189
+ * Cross-modal synchronization. Cognitive binding.
190
+ */
191
+ declare const GAMMA_PRESET: BrainwavePreset;
192
+ /**
193
+ * All available brainwave presets
194
+ */
195
+ declare const BRAINWAVE_PRESETS: Record<BrainwaveBand, BrainwavePreset>;
196
+ /**
197
+ * Get preset by ID
198
+ */
199
+ declare function getPreset(band: BrainwaveBand): BrainwavePreset;
200
+ /**
201
+ * Get preset by frequency (finds closest matching preset)
202
+ */
203
+ declare function getPresetByFrequency(frequency: number): BrainwavePreset | null;
204
+ /**
205
+ * Validate carrier frequency against Oster Curve (400-500 Hz for binaural beats)
206
+ */
207
+ declare function validateOsterCurve(carrierFrequency: number): boolean;
208
+ /**
209
+ * Get recommended carrier frequency (middle of Oster Curve)
210
+ */
211
+ declare function getRecommendedCarrierFrequency(): number;
212
+
213
+ /**
214
+ * Safety Warnings and Contraindications
215
+ *
216
+ * Safety protocols for auditory stimulation and brainwave entrainment
217
+ */
218
+
219
+ /**
220
+ * Safety warning messages
221
+ */
222
+ interface SafetyWarningMessage {
223
+ id: string;
224
+ title: string;
225
+ message: string;
226
+ severity: 'info' | 'warning' | 'critical';
227
+ }
228
+ /**
229
+ * Epilepsy warning (especially for visualizers)
230
+ * Musicogenic epilepsy is rare but non-zero risk
231
+ */
232
+ declare const EPILEPSY_WARNING: SafetyWarningMessage;
233
+ /**
234
+ * Driving warning (especially for Alpha/Theta/Delta)
235
+ * Can induce drowsiness and altered states
236
+ */
237
+ declare const DRIVING_WARNING: SafetyWarningMessage;
238
+ /**
239
+ * Pacemaker warning
240
+ * General headphone warning rather than specific to entrainment
241
+ */
242
+ declare const PACEMAKER_WARNING: SafetyWarningMessage;
243
+ /**
244
+ * Mental health warning
245
+ * Altered states can exacerbate certain conditions
246
+ */
247
+ declare const MENTAL_HEALTH_WARNING: SafetyWarningMessage;
248
+ /**
249
+ * Visual strobing warning (3-30 Hz range)
250
+ * Photosensitive epilepsy trigger
251
+ */
252
+ declare const STROBING_WARNING: SafetyWarningMessage;
253
+ /**
254
+ * Get safety warnings based on configuration
255
+ */
256
+ declare function getSafetyWarnings(config: {
257
+ hasVisualizer?: boolean;
258
+ currentPreset?: BrainwaveBand;
259
+ frequency?: number;
260
+ }): SafetyWarningMessage[];
261
+ /**
262
+ * Check if frequency is in photosensitive epilepsy trigger range (3-30 Hz)
263
+ */
264
+ declare function isPhotosensitiveTriggerRange(frequency: number): boolean;
265
+ /**
266
+ * Get all safety warnings
267
+ */
268
+ declare function getAllSafetyWarnings(): SafetyWarningMessage[];
269
+
270
+ /**
271
+ * Binaural Beat Generator
272
+ *
273
+ * Generates binaural beats using hard-panned oscillators (left/right channels).
274
+ * Requires carrier frequency between 400-500 Hz (Oster Curve) for maximum effectiveness.
275
+ *
276
+ * Key Principle:
277
+ * - Left Ear: Carrier Frequency (e.g., 200 Hz)
278
+ * - Right Ear: Carrier + Target Beat (e.g., 210 Hz for a 10 Hz Alpha state)
279
+ *
280
+ * The brain perceives a wavering beat at the difference frequency (10 Hz) in the Superior Olivary Complex.
281
+ */
282
+
283
+ interface BinauralNodes {
284
+ leftOsc: OscillatorNode;
285
+ rightOsc: OscillatorNode;
286
+ leftPan: StereoPannerNode;
287
+ rightPan: StereoPannerNode;
288
+ leftGain: GainNode;
289
+ rightGain: GainNode;
290
+ }
291
+ declare class BinauralGenerator {
292
+ private ctx;
293
+ private nodes;
294
+ private config;
295
+ constructor(ctx: AudioContext);
296
+ /**
297
+ * Start binaural beat generation
298
+ *
299
+ * @param config - Binaural generator configuration
300
+ * @param masterGain - Master gain node to connect to
301
+ */
302
+ start(config: BinauralConfig, masterGain: GainNode): void;
303
+ /**
304
+ * Update generator parameters
305
+ */
306
+ updateConfig(config: Partial<BinauralConfig>): void;
307
+ /**
308
+ * Stop binaural beat generation
309
+ */
310
+ stop(): void;
311
+ /**
312
+ * Check if generator is active
313
+ */
314
+ isActive(): boolean;
315
+ }
316
+
317
+ /**
318
+ * Isochronic Tone Generator
319
+ *
320
+ * Generates isochronic tones with 100% modulation depth.
321
+ * Uses gain envelopes with 5-10ms attack/release to prevent clicks (spectral splatter).
322
+ *
323
+ * Key Principle:
324
+ * - Single carrier tone is turned on and off at regular intervals
325
+ * - 100% modulation depth (silence to full volume) creates sharp rhythmic stimulus
326
+ * - Envelope shaping prevents speaker cone discontinuities that cause clicks
327
+ */
328
+
329
+ interface IsochronicNodes {
330
+ carrier: OscillatorNode;
331
+ gainNode: GainNode;
332
+ scheduledEvents: number[];
333
+ }
334
+ declare class IsochronicGenerator {
335
+ private ctx;
336
+ private nodes;
337
+ private config;
338
+ private isPlaying;
339
+ private lookaheadTimer;
340
+ private nextEventTime;
341
+ private scheduleAheadTime;
342
+ constructor(ctx: AudioContext);
343
+ /**
344
+ * Start isochronic tone generation
345
+ *
346
+ * @param config - Isochronic generator configuration
347
+ * @param masterGain - Master gain node to connect to
348
+ */
349
+ start(config: IsochronicConfig, masterGain: GainNode): void;
350
+ /**
351
+ * Schedule isochronic pulses using lookahead scheduling
352
+ * Prevents CPU overload by scheduling 1-2 seconds ahead
353
+ */
354
+ private schedulePulses;
355
+ /**
356
+ * Update generator parameters
357
+ */
358
+ updateConfig(config: Partial<IsochronicConfig>): void;
359
+ /**
360
+ * Stop isochronic tone generation
361
+ */
362
+ stop(): void;
363
+ /**
364
+ * Check if generator is active
365
+ */
366
+ isActive(): boolean;
367
+ }
368
+
369
+ /**
370
+ * Monaural Beat Generator
371
+ *
372
+ * Generates monaural beats using physical interference between two frequencies.
373
+ * Unlike binaural beats (which require headphones), monaural beats are created by
374
+ * mixing two frequencies in the same channel, creating a physical beat that can
375
+ * be heard through speakers.
376
+ *
377
+ * Key Principle:
378
+ * - Frequency 1: Base frequency (e.g., 200 Hz)
379
+ * - Frequency 2: Base + Beat frequency (e.g., 210 Hz for a 10 Hz Alpha state)
380
+ * - The two frequencies are mixed, creating a physical interference pattern
381
+ * - The beat frequency is the difference between the two frequencies
382
+ */
383
+
384
+ interface MonauralNodes {
385
+ osc1: OscillatorNode;
386
+ osc2: OscillatorNode;
387
+ gainNode: GainNode;
388
+ }
389
+ declare class MonauralGenerator {
390
+ private ctx;
391
+ private nodes;
392
+ private config;
393
+ constructor(ctx: AudioContext);
394
+ /**
395
+ * Start monaural beat generation
396
+ *
397
+ * @param config - Monaural generator configuration
398
+ * @param masterGain - Master gain node to connect to
399
+ */
400
+ start(config: MonauralConfig, masterGain: GainNode): void;
401
+ /**
402
+ * Update generator parameters
403
+ */
404
+ updateConfig(config: Partial<MonauralConfig>): void;
405
+ /**
406
+ * Stop monaural beat generation
407
+ */
408
+ stop(): void;
409
+ /**
410
+ * Check if generator is active
411
+ */
412
+ isActive(): boolean;
413
+ }
414
+
415
+ /**
416
+ * Brown Noise Generator
417
+ *
418
+ * Generates brown noise (1/f² power density) - the most soothing colored noise.
419
+ * Power density decreases by 6 dB per octave, heavily attenuating high frequencies.
420
+ * Results in a deep, rumbling texture similar to distant thunderstorm or large waterfall.
421
+ *
422
+ * Algorithm: Integrate white noise
423
+ * output = (lastOutput + (0.02 * whiteNoise)) / 1.02
424
+ */
425
+ interface BrownNoiseNodes {
426
+ bufferSource: AudioBufferSourceNode;
427
+ gainNode: GainNode;
428
+ }
429
+ declare class BrownNoiseGenerator {
430
+ private ctx;
431
+ private nodes;
432
+ private volume;
433
+ private buffer;
434
+ constructor(ctx: AudioContext);
435
+ /**
436
+ * Create brown noise buffer
437
+ * Generates a seamless loop of brown noise
438
+ */
439
+ private createBrownNoiseBuffer;
440
+ /**
441
+ * Start brown noise generation
442
+ *
443
+ * @param volume - Volume level (0.0 to 1.0)
444
+ * @param masterGain - Master gain node to connect to
445
+ */
446
+ start(volume: number, masterGain: GainNode): void;
447
+ /**
448
+ * Update volume
449
+ */
450
+ updateVolume(volume: number): void;
451
+ /**
452
+ * Stop brown noise generation
453
+ */
454
+ stop(): void;
455
+ /**
456
+ * Check if generator is active
457
+ */
458
+ isActive(): boolean;
459
+ }
460
+
461
+ /**
462
+ * Pink Noise Generator
463
+ *
464
+ * Generates pink noise (1/f power density) - balanced colored noise.
465
+ * Power density decreases by 3 dB per octave, providing a more balanced
466
+ * frequency spectrum than brown noise.
467
+ * Results in a texture similar to steady rain or rustling leaves.
468
+ *
469
+ * Algorithm: Filtered white noise with 1/f spectral characteristics
470
+ */
471
+ interface PinkNoiseNodes {
472
+ bufferSource: AudioBufferSourceNode;
473
+ gainNode: GainNode;
474
+ }
475
+ declare class PinkNoiseGenerator {
476
+ private ctx;
477
+ private nodes;
478
+ private volume;
479
+ private buffer;
480
+ constructor(ctx: AudioContext);
481
+ /**
482
+ * Create pink noise buffer
483
+ * Generates a seamless loop of pink noise using Voss-McCartney algorithm
484
+ */
485
+ private createPinkNoiseBuffer;
486
+ /**
487
+ * Start pink noise generation
488
+ *
489
+ * @param volume - Volume level (0.0 to 1.0)
490
+ * @param masterGain - Master gain node to connect to
491
+ */
492
+ start(volume: number, masterGain: GainNode): void;
493
+ /**
494
+ * Update volume
495
+ */
496
+ updateVolume(volume: number): void;
497
+ /**
498
+ * Stop pink noise generation
499
+ */
500
+ stop(): void;
501
+ /**
502
+ * Check if generator is active
503
+ */
504
+ isActive(): boolean;
505
+ }
506
+
507
+ /**
508
+ * Entrainment Engine
509
+ *
510
+ * Main coordinator class for brainwave entrainment system.
511
+ * Manages AudioContext, master gain, and all audio generators.
512
+ */
513
+
514
+ declare class EntrainmentEngine {
515
+ private ctx;
516
+ private masterGain;
517
+ private binauralGenerator;
518
+ private isochronicGenerator;
519
+ private monauralGenerator;
520
+ private brownNoiseGenerator;
521
+ private pinkNoiseGenerator;
522
+ private config;
523
+ private state;
524
+ private sessionStartTime;
525
+ private currentFrequency;
526
+ private targetFrequency;
527
+ private rampingInterval;
528
+ /**
529
+ * Initialize AudioContext
530
+ * Must be called from user gesture (button click) due to browser autoplay policy
531
+ */
532
+ initialize(): Promise<void>;
533
+ /**
534
+ * Resume AudioContext if suspended
535
+ * Required due to browser autoplay policy
536
+ */
537
+ resume(): Promise<void>;
538
+ /**
539
+ * Start entrainment with configuration
540
+ */
541
+ start(config: EntrainmentConfig): Promise<void>;
542
+ /**
543
+ * Progressive ramping system for gradual frequency transitions
544
+ * Prevents jumping too far from current state (entrainment best practice)
545
+ */
546
+ private startProgressiveRamp;
547
+ /**
548
+ * Start generators with specific frequency
549
+ */
550
+ private startGeneratorsWithFrequency;
551
+ /**
552
+ * Update frequency in active generators
553
+ */
554
+ private updateFrequencyInGenerators;
555
+ /**
556
+ * Stop entrainment
557
+ */
558
+ stop(): void;
559
+ /**
560
+ * Pause entrainment
561
+ */
562
+ pause(): void;
563
+ /**
564
+ * Resume entrainment
565
+ */
566
+ resumePlayback(): Promise<void>;
567
+ /**
568
+ * Update configuration (for real-time parameter changes)
569
+ */
570
+ updateConfig(config: Partial<EntrainmentConfig>): void;
571
+ /**
572
+ * Get current session information
573
+ */
574
+ getSessionInfo(): SessionInfo;
575
+ /**
576
+ * Get AudioContext (for visualization/analysis)
577
+ */
578
+ getContext(): AudioContext | null;
579
+ /**
580
+ * Get master gain node (for visualization/analysis)
581
+ */
582
+ getMasterGain(): GainNode | null;
583
+ /**
584
+ * Cleanup - disconnect all nodes and close AudioContext
585
+ */
586
+ cleanup(): void;
587
+ }
588
+
589
+ export { ALPHA_PRESET, BRAINWAVE_PRESETS, type BinauralConfig, BinauralGenerator, type BinauralNodes, type BrainwaveBand, type BrainwavePreset, type BrownNoiseConfig, BrownNoiseGenerator, type BrownNoiseNodes, DELTA_PRESET, DRIVING_WARNING, EPILEPSY_WARNING, type EntrainmentConfig, EntrainmentEngine, type EntrainmentSettings, GAMMA_PRESET, type GeneratorConfig, type GeneratorType, HIGH_BETA_PRESET, type IsochronicConfig, IsochronicGenerator, type IsochronicNodes, LOW_BETA_PRESET, MENTAL_HEALTH_WARNING, MID_BETA_PRESET, type MonauralConfig, MonauralGenerator, type MonauralNodes, PACEMAKER_WARNING, type PinkNoiseConfig, PinkNoiseGenerator, type PinkNoiseNodes, type PlaybackState, STROBING_WARNING, type SafetyWarningMessage, type SafetyWarnings, type SessionInfo, THETA_PRESET, getAllSafetyWarnings, getPreset, getPresetByFrequency, getRecommendedCarrierFrequency, getSafetyWarnings, isPhotosensitiveTriggerRange, validateOsterCurve };