2024-05-03 18:31:14 +00:00
|
|
|
import { TestAudioBuffer } from "./compare/index.js";
|
|
|
|
import { OfflineContext } from "../../Tone/core/context/OfflineContext.js";
|
|
|
|
import { getContext, setContext } from "../../Tone/core/Global.js";
|
|
|
|
import { Seconds } from "../../Tone/core/type/Units.js";
|
|
|
|
import { isArray, isFunction } from "../../Tone/core/util/TypeCheck.js";
|
2019-05-23 18:00:49 +00:00
|
|
|
|
|
|
|
type ReturnFunction = (time: Seconds) => void;
|
2019-04-12 14:37:47 +00:00
|
|
|
|
|
|
|
export async function Offline(
|
2024-05-03 18:31:14 +00:00
|
|
|
callback: (
|
|
|
|
context: OfflineContext
|
|
|
|
) =>
|
|
|
|
| void
|
|
|
|
| ReturnFunction
|
|
|
|
| ReturnFunction[]
|
|
|
|
| Promise<void | ReturnFunction>
|
|
|
|
| void,
|
|
|
|
duration = 0.1,
|
|
|
|
channels = 1,
|
|
|
|
sampleRate = 44100
|
2019-06-24 17:41:38 +00:00
|
|
|
): Promise<TestAudioBuffer> {
|
2019-06-23 19:02:38 +00:00
|
|
|
const originalContext = getContext();
|
2024-05-03 18:31:14 +00:00
|
|
|
const offline = new OfflineContext(
|
|
|
|
channels,
|
|
|
|
duration + 1 / sampleRate,
|
|
|
|
sampleRate
|
|
|
|
);
|
2019-06-23 19:02:38 +00:00
|
|
|
setContext(offline);
|
2019-11-18 19:47:18 +00:00
|
|
|
try {
|
|
|
|
let retFunction = callback(offline);
|
|
|
|
if (retFunction instanceof Promise) {
|
|
|
|
retFunction = await retFunction;
|
|
|
|
}
|
|
|
|
if (isFunction(retFunction)) {
|
|
|
|
const fn = retFunction;
|
2019-08-09 23:51:39 +00:00
|
|
|
offline.on("tick", () => fn(offline.now()));
|
2019-11-18 19:47:18 +00:00
|
|
|
} else if (isArray(retFunction)) {
|
|
|
|
// each element in the array is a timing callback
|
2024-05-03 18:31:14 +00:00
|
|
|
retFunction.forEach((fn) => {
|
2019-11-18 19:47:18 +00:00
|
|
|
offline.on("tick", () => fn(offline.now()));
|
|
|
|
});
|
|
|
|
}
|
2019-11-18 20:08:12 +00:00
|
|
|
} catch (e) {
|
|
|
|
throw e;
|
2019-11-18 19:47:18 +00:00
|
|
|
} finally {
|
|
|
|
setContext(originalContext);
|
2019-11-18 20:08:12 +00:00
|
|
|
const buffer = await offline.render();
|
|
|
|
return new TestAudioBuffer(buffer.get() as AudioBuffer);
|
2019-05-23 18:00:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-03 18:31:14 +00:00
|
|
|
export function whenBetween(
|
|
|
|
value: Seconds,
|
|
|
|
start: Seconds,
|
|
|
|
stop: Seconds,
|
|
|
|
callback: () => void
|
|
|
|
): void {
|
2019-05-23 18:00:49 +00:00
|
|
|
if (value >= start && value < stop) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// invoked only once
|
2024-05-03 18:31:14 +00:00
|
|
|
export function atTime(
|
|
|
|
when: Seconds,
|
|
|
|
callback: (time: Seconds) => void
|
|
|
|
): (time: Seconds) => void {
|
2019-05-23 18:00:49 +00:00
|
|
|
let wasInvoked = false;
|
|
|
|
return (time) => {
|
|
|
|
if (time >= when && !wasInvoked) {
|
|
|
|
callback(time);
|
|
|
|
wasInvoked = true;
|
|
|
|
}
|
|
|
|
};
|
2019-04-12 14:37:47 +00:00
|
|
|
}
|