0
# Core Audio System
1
2
The core audio system provides global audio context management, time utilities, and fundamental audio types that form the foundation for all Tone.js applications.
3
4
## Capabilities
5
6
### Audio Context Management
7
8
Control the global audio context and initialization.
9
10
```typescript { .api }
11
/**
12
* Start the audio context. Required before any audio can be played.
13
* Must be called from a user interaction event handler.
14
* @returns Promise that resolves when audio is ready
15
*/
16
function start(): Promise<void>;
17
18
/**
19
* Get the current audio context time in seconds
20
* @returns Current audio context time
21
*/
22
function now(): number;
23
24
/**
25
* Get the current audio context time without lookAhead offset
26
* @returns Immediate audio context time
27
*/
28
function immediate(): number;
29
30
/**
31
* Get the global Tone.js context
32
* @returns The global context instance
33
*/
34
function getContext(): Context;
35
36
/**
37
* Set a custom audio context as the global context
38
* @param context - Custom AudioContext to use
39
*/
40
function setContext(context: BaseAudioContext): void;
41
42
/**
43
* Check if Web Audio API is supported in the current browser
44
*/
45
const supported: boolean;
46
```
47
48
**Usage Examples:**
49
50
```typescript
51
import { start, now, getContext } from "tone";
52
53
// Start audio from user interaction
54
document.addEventListener("click", async () => {
55
await start();
56
console.log("Audio context started");
57
58
// Get current time for scheduling
59
const currentTime = now();
60
console.log("Current time:", currentTime);
61
});
62
63
// Check support
64
if (!supported) {
65
console.warn("Web Audio API not supported");
66
}
67
```
68
69
### Global Singletons
70
71
Access global audio system components.
72
73
```typescript { .api }
74
/**
75
* Get the global Transport instance for timing and scheduling
76
* @returns Global transport instance
77
*/
78
function getTransport(): TransportInstance;
79
80
/**
81
* Get the global Destination (output) instance
82
* @returns Global destination instance
83
*/
84
function getDestination(): DestinationInstance;
85
86
/**
87
* Get the global Listener instance for 3D audio positioning
88
* @returns Global listener instance
89
*/
90
function getListener(): ListenerInstance;
91
92
/**
93
* Get the global Draw instance for animation synchronization
94
* @returns Global draw instance
95
*/
96
function getDraw(): DrawInstance;
97
```
98
99
### Audio Buffer Management
100
101
Utilities for loading and managing audio buffers.
102
103
```typescript { .api }
104
/**
105
* Promise that resolves when all ToneAudioBuffers have finished loading
106
* @returns Promise that resolves when all audio is loaded
107
*/
108
function loaded(): Promise<void>;
109
110
/**
111
* Audio buffer wrapper with additional functionality
112
*/
113
class ToneAudioBuffer {
114
constructor(url?: string | AudioBuffer, onload?: () => void, onerror?: (error: Error) => void);
115
116
/** The underlying AudioBuffer */
117
buffer: AudioBuffer | null;
118
119
/** Duration of the buffer in seconds */
120
duration: number;
121
122
/** Sample rate of the buffer */
123
sampleRate: number;
124
125
/** Number of channels in the buffer */
126
numberOfChannels: number;
127
128
/** Load audio from URL */
129
load(url: string): Promise<ToneAudioBuffer>;
130
131
/** Get channel data as Float32Array */
132
getChannelData(channel: number): Float32Array;
133
134
/** Convert buffer to array */
135
toArray(): number[] | number[][];
136
137
/** Reverse the buffer */
138
reverse(): ToneAudioBuffer;
139
140
/** Slice the buffer */
141
slice(start: number, end?: number): ToneAudioBuffer;
142
143
/** Static method to check if all buffers are loaded */
144
static loaded(): Promise<void>;
145
}
146
147
/**
148
* Collection of named audio buffers
149
*/
150
class ToneAudioBuffers {
151
constructor(urls: {[name: string]: string} | ToneAudioBuffer[], baseUrl?: string, onload?: () => void);
152
153
/** Get buffer by name */
154
get(name: string): ToneAudioBuffer;
155
156
/** Check if buffer exists */
157
has(name: string): boolean;
158
159
/** Add buffer */
160
add(name: string, url: string | ToneAudioBuffer, callback?: () => void): ToneAudioBuffers;
161
}
162
163
/**
164
* Deprecated aliases for backward compatibility
165
*/
166
167
/** @deprecated Use ToneAudioBuffer instead */
168
const Buffer: typeof ToneAudioBuffer;
169
170
/** @deprecated Use ToneAudioBuffers instead */
171
const Buffers: typeof ToneAudioBuffers;
172
173
/** @deprecated Use ToneBufferSource instead */
174
const BufferSource: typeof ToneBufferSource;
175
```
176
177
### Time and Frequency Types
178
179
Advanced time and frequency value classes with unit conversions.
180
181
```typescript { .api }
182
/**
183
* Time value with unit conversion support
184
*/
185
class Time {
186
constructor(value: Time, units?: string);
187
188
/** Convert to seconds */
189
toSeconds(): number;
190
191
/** Convert to frequency */
192
toFrequency(): number;
193
194
/** Convert to ticks */
195
toTicks(): number;
196
197
/** Convert to samples */
198
toSamples(): number;
199
200
/** Convert to musical notation */
201
toNotation(): string;
202
203
/** Convert to milliseconds */
204
toMilliseconds(): number;
205
206
/** Add time values */
207
add(value: Time): Time;
208
209
/** Subtract time values */
210
sub(value: Time): Time;
211
212
/** Multiply time values */
213
mult(value: number): Time;
214
215
/** Divide time values */
216
div(value: number): Time;
217
}
218
219
/**
220
* Frequency value with unit conversion support
221
*/
222
class Frequency {
223
constructor(value: Frequency, units?: string);
224
225
/** Convert to hertz */
226
toFrequency(): number;
227
228
/** Convert to MIDI note number */
229
toMidi(): number;
230
231
/** Convert to note name */
232
toNote(): string;
233
234
/** Convert to cents */
235
toCents(): number;
236
237
/** Transpose by semitones */
238
transpose(semitones: number): Frequency;
239
240
/** Harmonize with interval */
241
harmonize(intervals: number[]): Frequency[];
242
}
243
244
/**
245
* MIDI note number representation
246
*/
247
class Midi {
248
constructor(value: number);
249
250
/** Convert to frequency */
251
toFrequency(): number;
252
253
/** Convert to note name */
254
toNote(): string;
255
256
/** Transpose by semitones */
257
transpose(semitones: number): Midi;
258
}
259
```
260
261
### Core Audio Nodes
262
263
Fundamental audio node wrappers.
264
265
```typescript { .api }
266
/**
267
* Base class for all Tone.js audio nodes
268
*/
269
class ToneAudioNode {
270
constructor(options?: Partial<ToneAudioNodeOptions>);
271
272
/** Audio context */
273
context: Context;
274
275
/** Number of inputs */
276
numberOfInputs: number;
277
278
/** Number of outputs */
279
numberOfOutputs: number;
280
281
/** Connect to another node */
282
connect(destination: AudioNode | ToneAudioNode, outputNumber?: number, inputNumber?: number): this;
283
284
/** Disconnect from other nodes */
285
disconnect(destination?: AudioNode | ToneAudioNode, outputNumber?: number, inputNumber?: number): this;
286
287
/** Connect to destination and return destination */
288
toDestination(): this;
289
290
/** Dispose of the node */
291
dispose(): this;
292
293
/** Get the audio node */
294
get(): AudioNode;
295
}
296
297
/**
298
* Gain node wrapper with additional functionality
299
*/
300
class Gain extends ToneAudioNode {
301
constructor(gain?: number, units?: string);
302
303
/** Gain parameter */
304
gain: Param<"decibels" | "gain">;
305
}
306
307
/**
308
* Delay node wrapper with additional functionality
309
*/
310
class Delay extends ToneAudioNode {
311
constructor(delayTime?: Time, maxDelay?: number);
312
313
/** Delay time parameter */
314
delayTime: Param<"time">;
315
}
316
317
/**
318
* Audio parameter with automation and unit conversion
319
*/
320
class Param<T extends UnitName = "number"> {
321
constructor(param: AudioParam, units?: T, convert?: boolean);
322
323
/** Current value */
324
value: UnitMap[T];
325
326
/** Set value at specific time */
327
setValueAtTime(value: UnitMap[T], time: Time): this;
328
329
/** Linear ramp to value */
330
linearRampToValueAtTime(value: UnitMap[T], time: Time): this;
331
332
/** Exponential ramp to value */
333
exponentialRampToValueAtTime(value: UnitMap[T], time: Time): this;
334
335
/** Ramp to value over duration */
336
rampTo(value: UnitMap[T], time: Time, startTime?: Time): this;
337
338
/** Target value with time constant */
339
targetRampTo(value: UnitMap[T], time: Time, startTime?: Time): this;
340
341
/** Cancel scheduled changes */
342
cancelScheduledValues(time: Time): this;
343
344
/** Convert to units */
345
convert: boolean;
346
347
/** Parameter units */
348
units: T;
349
}
350
```
351
352
### Utility Classes and Functions
353
354
Core utilities for audio development.
355
356
```typescript { .api }
357
/**
358
* Conversion functions
359
*/
360
361
/** Convert decibels to gain */
362
function dbToGain(db: number): number;
363
364
/** Convert gain to decibels */
365
function gainToDb(gain: number): number;
366
367
/** Convert frequency to MIDI note number */
368
function ftom(frequency: number): number;
369
370
/** Convert MIDI note number to frequency */
371
function mtof(midi: number): number;
372
373
/** Convert interval in semitones to frequency ratio */
374
function intervalToFrequencyRatio(interval: number): number;
375
376
/**
377
* Argument handling utilities
378
*/
379
380
/** Provide default values for undefined arguments */
381
function defaultArg<T>(value: T | undefined, defaultValue: T): T;
382
383
/** Parse constructor arguments into options object */
384
function optionsFromArguments<T>(defaults: T, args: IArguments): T;
385
386
/**
387
* Timeline classes for event scheduling
388
*/
389
class Timeline<T> {
390
constructor();
391
392
/** Add event to timeline */
393
add(event: TimelineEvent<T>): Timeline<T>;
394
395
/** Remove event from timeline */
396
remove(event: TimelineEvent<T>): Timeline<T>;
397
398
/** Get events at specific time */
399
get(time: number): T[];
400
401
/** Cancel events after time */
402
cancel(time: number): Timeline<T>;
403
404
/** Clear all events */
405
clear(): Timeline<T>;
406
}
407
408
class IntervalTimeline extends Timeline<any> {
409
/** Add interval event */
410
add(event: IntervalTimelineEvent): IntervalTimeline;
411
412
/** Get events at time */
413
get(time: number): IntervalTimelineEvent[];
414
}
415
416
class StateTimeline<T> extends Timeline<T> {
417
/** Get state at time */
418
getValueAtTime(time: number): T | null;
419
420
/** Set state at time */
421
setStateAtTime(state: T, time: number): StateTimeline<T>;
422
}
423
```
424
425
## Types
426
427
```typescript { .api }
428
interface Context extends BaseAudioContext {
429
now(): number;
430
immediate(): number;
431
lookAhead: number;
432
updateInterval: number;
433
transport: TransportInstance;
434
destination: DestinationInstance;
435
listener: ListenerInstance;
436
draw: DrawInstance;
437
}
438
439
interface ToneAudioNodeOptions {
440
context?: Context;
441
}
442
443
interface TimelineEvent<T> {
444
time: number;
445
value: T;
446
}
447
448
interface IntervalTimelineEvent extends TimelineEvent<any> {
449
duration: number;
450
}
451
452
type UnitMap = {
453
number: number;
454
frequency: number;
455
time: number;
456
decibels: number;
457
normalRange: number;
458
positive: number;
459
cents: number;
460
degrees: number;
461
gain: number;
462
bpm: number;
463
};
464
```