Tone.js/test/helper/Offline.ts

44 lines
1.4 KiB
TypeScript
Raw Normal View History

2019-05-23 18:00:49 +00:00
import { TestAudioBuffer } from "@tonejs/plot";
import { Context } from "Tone/core/context/Context";
import { OfflineContext } from "Tone/core/context/OfflineContext";
import { isFunction } from "Tone/core/util/TypeCheck";
type ReturnFunction = (time: Seconds) => void;
2019-04-12 14:37:47 +00:00
export async function Offline(
2019-05-23 18:00:49 +00:00
callback: (context: OfflineContext) => void | ReturnFunction | Promise<void | ReturnFunction> | void,
2019-06-18 01:49:38 +00:00
duration = 0.1, channels = 1, sampleRate: number = 44100,
2019-04-12 14:37:47 +00:00
) {
2019-05-23 18:00:49 +00:00
const originalContext = Context.getGlobal();
2019-06-18 01:49:38 +00:00
const offline = new OfflineContext(channels, duration + 1 / sampleRate, sampleRate);
2019-05-23 18:00:49 +00:00
Context.setGlobal(offline);
let retFunction = callback(offline);
if (retFunction instanceof Promise) {
retFunction = await retFunction;
}
if (isFunction(retFunction)) {
const fn = retFunction;
offline.on("tick", () => fn(offline.now()));
}
Context.setGlobal(originalContext);
const buffer = await offline.render();
return new TestAudioBuffer(buffer);
}
export function whenBetween(value: Seconds, start: Seconds, stop: Seconds, callback: () => void): void {
if (value >= start && value < stop) {
callback();
}
}
// invoked only once
export function atTime(when: Seconds, callback: (time: Seconds) => void): (time: Seconds) => void {
let wasInvoked = false;
return (time) => {
if (time >= when && !wasInvoked) {
callback(time);
wasInvoked = true;
}
};
2019-04-12 14:37:47 +00:00
}