UNPKG

2.49 kBJavaScriptView Raw
1import { __awaiter } from "tslib";
2import { getContext, setContext } from "../Global.js";
3import { OfflineContext } from "./OfflineContext.js";
4import { ToneAudioBuffer } from "./ToneAudioBuffer.js";
5import "./Destination.js";
6import "./Listener.js";
7/**
8 * Generate a buffer by rendering all of the Tone.js code within the callback using the OfflineAudioContext.
9 * The OfflineAudioContext is capable of rendering much faster than real time in many cases.
10 * The callback function also passes in an offline instance of {@link Context} which can be used
11 * to schedule events along the Transport.
12 * @param callback All Tone.js nodes which are created and scheduled within this callback are recorded into the output Buffer.
13 * @param duration the amount of time to record for.
14 * @return The promise which is invoked with the ToneAudioBuffer of the recorded output.
15 * @example
16 * // render 2 seconds of the oscillator
17 * Tone.Offline(() => {
18 * // only nodes created in this callback will be recorded
19 * const oscillator = new Tone.Oscillator().toDestination().start(0);
20 * }, 2).then((buffer) => {
21 * // do something with the output buffer
22 * console.log(buffer);
23 * });
24 * @example
25 * // can also schedule events along the Transport
26 * // using the passed in Offline Transport
27 * Tone.Offline(({ transport }) => {
28 * const osc = new Tone.Oscillator().toDestination();
29 * transport.schedule(time => {
30 * osc.start(time).stop(time + 0.1);
31 * }, 1);
32 * // make sure to start the transport
33 * transport.start(0.2);
34 * }, 4).then((buffer) => {
35 * // do something with the output buffer
36 * console.log(buffer);
37 * });
38 * @category Core
39 */
40export function Offline(callback_1, duration_1) {
41 return __awaiter(this, arguments, void 0, function* (callback, duration, channels = 2, sampleRate = getContext().sampleRate) {
42 // set the OfflineAudioContext based on the current context
43 const originalContext = getContext();
44 const context = new OfflineContext(channels, duration, sampleRate);
45 setContext(context);
46 // invoke the callback/scheduling
47 yield callback(context);
48 // then render the audio
49 const bufferPromise = context.render();
50 // return the original AudioContext
51 setContext(originalContext);
52 // await the rendering
53 const buffer = yield bufferPromise;
54 // return the audio
55 return new ToneAudioBuffer(buffer);
56 });
57}
58//# sourceMappingURL=Offline.js.map
\No newline at end of file