UNPKG

9.65 kBTypeScriptView Raw
1import { TickerClockSource } from "../clock/Ticker.js";
2import { Seconds } from "../type/Units.js";
3import { AnyAudioContext } from "./AudioContext.js";
4import { BaseContext, ContextLatencyHint } from "./BaseContext.js";
5import type { DrawClass as Draw } from "../util/Draw.js";
6import type { DestinationClass as Destination } from "./Destination.js";
7import type { TransportClass as Transport } from "../clock/Transport.js";
8import type { ListenerClass as Listener } from "./Listener.js";
9export interface ContextOptions {
10 clockSource: TickerClockSource;
11 latencyHint: ContextLatencyHint;
12 lookAhead: Seconds;
13 updateInterval: Seconds;
14 context: AnyAudioContext;
15}
16export interface ContextTimeoutEvent {
17 callback: (...args: any[]) => void;
18 id: number;
19 time: Seconds;
20}
21/**
22 * Wrapper around the native AudioContext.
23 * @category Core
24 */
25export declare class Context extends BaseContext {
26 readonly name: string;
27 /**
28 * private reference to the BaseAudioContext
29 */
30 protected readonly _context: AnyAudioContext;
31 /**
32 * A reliable callback method
33 */
34 private readonly _ticker;
35 /**
36 * The default latency hint
37 */
38 private _latencyHint;
39 /**
40 * An object containing all of the constants AudioBufferSourceNodes
41 */
42 private _constants;
43 /**
44 * All of the setTimeout events.
45 */
46 private _timeouts;
47 /**
48 * The timeout id counter
49 */
50 private _timeoutIds;
51 /**
52 * A reference the Transport singleton belonging to this context
53 */
54 private _transport;
55 /**
56 * A reference the Listener singleton belonging to this context
57 */
58 private _listener;
59 /**
60 * A reference the Destination singleton belonging to this context
61 */
62 private _destination;
63 /**
64 * A reference the Transport singleton belonging to this context
65 */
66 private _draw;
67 /**
68 * Private indicator if the context has been initialized
69 */
70 private _initialized;
71 /**
72 * Private indicator if a close() has been called on the context, since close is async
73 */
74 private _closeStarted;
75 /**
76 * Indicates if the context is an OfflineAudioContext or an AudioContext
77 */
78 readonly isOffline: boolean;
79 constructor(context?: AnyAudioContext);
80 constructor(options?: Partial<ContextOptions>);
81 static getDefaults(): ContextOptions;
82 /**
83 * Finish setting up the context. **You usually do not need to do this manually.**
84 */
85 private initialize;
86 createAnalyser(): AnalyserNode;
87 createOscillator(): OscillatorNode;
88 createBufferSource(): AudioBufferSourceNode;
89 createBiquadFilter(): BiquadFilterNode;
90 createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer;
91 createChannelMerger(numberOfInputs?: number | undefined): ChannelMergerNode;
92 createChannelSplitter(numberOfOutputs?: number | undefined): ChannelSplitterNode;
93 createConstantSource(): ConstantSourceNode;
94 createConvolver(): ConvolverNode;
95 createDelay(maxDelayTime?: number | undefined): DelayNode;
96 createDynamicsCompressor(): DynamicsCompressorNode;
97 createGain(): GainNode;
98 createIIRFilter(feedForward: number[] | Float32Array, feedback: number[] | Float32Array): IIRFilterNode;
99 createPanner(): PannerNode;
100 createPeriodicWave(real: number[] | Float32Array, imag: number[] | Float32Array, constraints?: PeriodicWaveConstraints | undefined): PeriodicWave;
101 createStereoPanner(): StereoPannerNode;
102 createWaveShaper(): WaveShaperNode;
103 createMediaStreamSource(stream: MediaStream): MediaStreamAudioSourceNode;
104 createMediaElementSource(element: HTMLMediaElement): MediaElementAudioSourceNode;
105 createMediaStreamDestination(): MediaStreamAudioDestinationNode;
106 decodeAudioData(audioData: ArrayBuffer): Promise<AudioBuffer>;
107 /**
108 * The current time in seconds of the AudioContext.
109 */
110 get currentTime(): Seconds;
111 /**
112 * The current time in seconds of the AudioContext.
113 */
114 get state(): AudioContextState;
115 /**
116 * The current time in seconds of the AudioContext.
117 */
118 get sampleRate(): number;
119 /**
120 * The listener
121 */
122 get listener(): Listener;
123 set listener(l: Listener);
124 /**
125 * There is only one Transport per Context. It is created on initialization.
126 */
127 get transport(): Transport;
128 set transport(t: Transport);
129 /**
130 * This is the Draw object for the context which is useful for synchronizing the draw frame with the Tone.js clock.
131 */
132 get draw(): Draw;
133 set draw(d: Draw);
134 /**
135 * A reference to the Context's destination node.
136 */
137 get destination(): Destination;
138 set destination(d: Destination);
139 /**
140 * Maps a module name to promise of the addModule method
141 */
142 private _workletPromise;
143 /**
144 * Create an audio worklet node from a name and options. The module
145 * must first be loaded using {@link addAudioWorkletModule}.
146 */
147 createAudioWorkletNode(name: string, options?: Partial<AudioWorkletNodeOptions>): AudioWorkletNode;
148 /**
149 * Add an AudioWorkletProcessor module
150 * @param url The url of the module
151 */
152 addAudioWorkletModule(url: string): Promise<void>;
153 /**
154 * Returns a promise which resolves when all of the worklets have been loaded on this context
155 */
156 protected workletsAreReady(): Promise<void>;
157 /**
158 * How often the interval callback is invoked.
159 * This number corresponds to how responsive the scheduling
160 * can be. Setting to 0 will result in the lowest practial interval
161 * based on context properties. context.updateInterval + context.lookAhead
162 * gives you the total latency between scheduling an event and hearing it.
163 */
164 get updateInterval(): Seconds;
165 set updateInterval(interval: Seconds);
166 /**
167 * What the source of the clock is, either "worker" (default),
168 * "timeout", or "offline" (none).
169 */
170 get clockSource(): TickerClockSource;
171 set clockSource(type: TickerClockSource);
172 /**
173 * The amount of time into the future events are scheduled. Giving Web Audio
174 * a short amount of time into the future to schedule events can reduce clicks and
175 * improve performance. This value can be set to 0 to get the lowest latency.
176 * Adjusting this value also affects the {@link updateInterval}.
177 */
178 get lookAhead(): Seconds;
179 set lookAhead(time: Seconds);
180 private _lookAhead;
181 /**
182 * The type of playback, which affects tradeoffs between audio
183 * output latency and responsiveness.
184 * In addition to setting the value in seconds, the latencyHint also
185 * accepts the strings "interactive" (prioritizes low latency),
186 * "playback" (prioritizes sustained playback), "balanced" (balances
187 * latency and performance).
188 * @example
189 * // prioritize sustained playback
190 * const context = new Tone.Context({ latencyHint: "playback" });
191 * // set this context as the global Context
192 * Tone.setContext(context);
193 * // the global context is gettable with Tone.getContext()
194 * console.log(Tone.getContext().latencyHint);
195 */
196 get latencyHint(): ContextLatencyHint | Seconds;
197 /**
198 * The unwrapped AudioContext or OfflineAudioContext
199 */
200 get rawContext(): AnyAudioContext;
201 /**
202 * The current audio context time plus a short {@link lookAhead}.
203 * @example
204 * setInterval(() => {
205 * console.log("now", Tone.now());
206 * }, 100);
207 */
208 now(): Seconds;
209 /**
210 * The current audio context time without the {@link lookAhead}.
211 * In most cases it is better to use {@link now} instead of {@link immediate} since
212 * with {@link now} the {@link lookAhead} is applied equally to _all_ components including internal components,
213 * to making sure that everything is scheduled in sync. Mixing {@link now} and {@link immediate}
214 * can cause some timing issues. If no lookAhead is desired, you can set the {@link lookAhead} to `0`.
215 */
216 immediate(): Seconds;
217 /**
218 * Starts the audio context from a suspended state. This is required
219 * to initially start the AudioContext.
220 * @see {@link start}
221 */
222 resume(): Promise<void>;
223 /**
224 * Close the context. Once closed, the context can no longer be used and
225 * any AudioNodes created from the context will be silent.
226 */
227 close(): Promise<void>;
228 /**
229 * **Internal** Generate a looped buffer at some constant value.
230 */
231 getConstant(val: number): AudioBufferSourceNode;
232 /**
233 * Clean up. Also closes the audio context.
234 */
235 dispose(): this;
236 /**
237 * The private loop which keeps track of the context scheduled timeouts
238 * Is invoked from the clock source
239 */
240 private _timeoutLoop;
241 /**
242 * A setTimeout which is guaranteed by the clock source.
243 * Also runs in the offline context.
244 * @param fn The callback to invoke
245 * @param timeout The timeout in seconds
246 * @returns ID to use when invoking Context.clearTimeout
247 */
248 setTimeout(fn: (...args: any[]) => void, timeout: Seconds): number;
249 /**
250 * Clears a previously scheduled timeout with Tone.context.setTimeout
251 * @param id The ID returned from setTimeout
252 */
253 clearTimeout(id: number): this;
254 /**
255 * Clear the function scheduled by {@link setInterval}
256 */
257 clearInterval(id: number): this;
258 /**
259 * Adds a repeating event to the context's callback clock
260 */
261 setInterval(fn: (...args: any[]) => void, interval: Seconds): number;
262}