Tone.js/Tone/event/ToneEvent.ts

396 lines
10 KiB
TypeScript
Raw Normal View History

2019-07-23 17:15:04 +00:00
import "../core/clock/Transport";
import { ToneWithContext, ToneWithContextOptions } from "../core/context/ToneWithContext";
import { TicksClass } from "../core/type/Ticks";
2019-07-25 17:32:34 +00:00
import { TransportTimeClass } from "../core/type/TransportTime";
import { NormalRange, Positive, Seconds, Ticks, Time, TransportTime } from "../core/type/Units";
2019-07-23 17:15:04 +00:00
import { defaultArg, optionsFromArguments } from "../core/util/Defaults";
import { noOp } from "../core/util/Interface";
import { BasicPlaybackState, StateTimeline } from "../core/util/StateTimeline";
2019-07-25 17:32:34 +00:00
import { isBoolean, isNumber } from "../core/util/TypeCheck";
2019-07-23 17:15:04 +00:00
export type ToneEventCallback<T> = (time: Seconds, value: T) => void;
2019-07-23 17:15:04 +00:00
export interface ToneEventOptions<T> extends ToneWithContextOptions {
callback: ToneEventCallback<T>;
2019-07-23 17:15:04 +00:00
loop: boolean | number;
loopEnd: Time;
loopStart: Time;
playbackRate: Positive;
value?: T;
2019-07-23 17:15:04 +00:00
probability: NormalRange;
mute: boolean;
humanize: boolean | Time;
}
/**
* ToneEvent abstracts away this.context.transport.schedule and provides a schedulable
* callback for a single or repeatable events along the timeline.
*
* @example
2019-10-24 22:01:27 +00:00
* import { PolySynth, Sequence, ToneEvent, Transport } from "tone";
*
* const synth = new PolySynth().toDestination();
* const chordEvent = new ToneEvent(((time, chord) => {
* // the chord as well as the exact time of the event
* // are passed in as arguments to the callback function
* synth.triggerAttackRelease(chord, 0.5, time);
* }), ["D4", "E4", "F4"]);
* // start the chord at the beginning of the transport timeline
* chordEvent.start();
* // loop it every measure for 8 measures
* chordEvent.loop = 8;
* chordEvent.loopEnd = "1m";
2019-09-16 14:49:30 +00:00
* @category Event
2019-07-23 17:15:04 +00:00
*/
export class ToneEvent<ValueType = any> extends ToneWithContext<ToneEventOptions<ValueType>> {
2019-07-23 17:15:04 +00:00
2019-09-04 22:38:04 +00:00
readonly name: string = "ToneEvent";
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* Loop value
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
protected _loop: boolean | number;
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* The callback to invoke.
2019-07-23 17:15:04 +00:00
*/
callback: ToneEventCallback<ValueType>;
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* The value which is passed to the
* callback function.
2019-07-23 17:15:04 +00:00
*/
value: ValueType;
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* When the note is scheduled to start.
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
protected _loopStart: Ticks;
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* When the note is scheduled to start.
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
protected _loopEnd: Ticks;
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* Tracks the scheduled events
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
protected _state: StateTimeline<{
2019-09-14 22:12:44 +00:00
id: number;
2019-07-23 19:17:45 +00:00
}> = new StateTimeline("stopped");
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* The playback speed of the note. A speed of 1
* is no change.
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
protected _playbackRate: Positive;
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* A delay time from when the event is scheduled to start
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
protected _startOffset: Ticks = 0;
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* private holder of probability value
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
protected _probability: NormalRange;
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* the amount of variation from the given time.
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
protected _humanize: boolean | Time;
2019-07-23 17:15:04 +00:00
/**
2019-09-14 20:39:18 +00:00
* If mute is true, the callback won't be invoked.
2019-07-23 17:15:04 +00:00
*/
mute: boolean;
2019-08-27 15:58:40 +00:00
/**
* @param callback The callback to invoke at the time.
* @param value The value or values which should be passed to the callback function on invocation.
*/
constructor(callback?: ToneEventCallback<ValueType>, value?: ValueType);
constructor(options?: Partial<ToneEventOptions<ValueType>>);
2019-07-23 17:15:04 +00:00
constructor() {
super(optionsFromArguments(ToneEvent.getDefaults(), arguments, ["callback", "value"]));
const options = optionsFromArguments(ToneEvent.getDefaults(), arguments, ["callback", "value"]);
this._loop = options.loop;
this.callback = options.callback;
this.value = options.value;
this._loopStart = this.toTicks(options.loopStart);
this._loopEnd = this.toTicks(options.loopEnd);
this._playbackRate = options.playbackRate;
this._probability = options.probability;
this._humanize = options.humanize;
this.mute = options.mute;
this.playbackRate = options.playbackRate;
}
static getDefaults(): ToneEventOptions<any> {
2019-07-23 17:15:04 +00:00
return Object.assign(ToneWithContext.getDefaults(), {
2019-09-14 22:12:44 +00:00
callback: noOp,
humanize: false,
loop: false,
loopEnd: "1m",
loopStart: 0,
mute: false,
playbackRate: 1,
probability: 1,
value: null,
2019-07-23 17:15:04 +00:00
});
}
/**
2019-09-14 20:39:18 +00:00
* Reschedule all of the events along the timeline
* with the updated values.
* @param after Only reschedules events after the given time.
2019-07-23 17:15:04 +00:00
*/
private _rescheduleEvents(after: Ticks = -1): void {
// if no argument is given, schedules all of the events
this._state.forEachFrom(after, event => {
let duration;
if (event.state === "started") {
if (event.id !== -1) {
2019-07-23 17:15:04 +00:00
this.context.transport.clear(event.id);
}
const startTick = event.time + Math.round(this.startOffset / this._playbackRate);
if (this._loop === true || isNumber(this._loop) && this._loop > 1) {
duration = Infinity;
if (isNumber(this._loop)) {
duration = (this._loop) * this._getLoopDuration();
}
const nextEvent = this._state.getAfter(startTick);
if (nextEvent !== null) {
duration = Math.min(duration, nextEvent.time - startTick);
}
if (duration !== Infinity) {
// schedule a stop since it's finite duration
2019-09-14 22:12:44 +00:00
this._state.setStateAtTime("stopped", startTick + duration + 1, { id: -1 });
2019-07-23 17:15:04 +00:00
duration = new TicksClass(this.context, duration);
}
const interval = new TicksClass(this.context, this._getLoopDuration());
event.id = this.context.transport.scheduleRepeat(
this._tick.bind(this), interval, new TicksClass(this.context, startTick), duration);
} else {
event.id = this.context.transport.schedule(this._tick.bind(this), new TicksClass(this.context, startTick));
}
}
});
}
/**
2019-09-14 20:39:18 +00:00
* Returns the playback state of the note, either "started" or "stopped".
2019-07-23 17:15:04 +00:00
*/
get state(): BasicPlaybackState {
return this._state.getValueAtTime(this.context.transport.ticks) as BasicPlaybackState;
2019-07-23 17:15:04 +00:00
}
/**
2019-07-23 19:17:45 +00:00
* The start from the scheduled start time.
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
get startOffset(): Ticks {
2019-07-23 17:15:04 +00:00
return this._startOffset;
}
2019-07-23 19:17:45 +00:00
set startOffset(offset) {
2019-07-23 17:15:04 +00:00
this._startOffset = offset;
}
/**
2019-09-14 20:39:18 +00:00
* The probability of the notes being triggered.
2019-07-23 17:15:04 +00:00
*/
get probability(): NormalRange {
return this._probability;
}
set probability(prob) {
this._probability = prob;
}
/**
2019-09-14 20:39:18 +00:00
* If set to true, will apply small random variation
* to the callback time. If the value is given as a time, it will randomize
* by that amount.
2019-07-23 17:15:04 +00:00
* @example
2019-10-25 20:54:33 +00:00
* import { ToneEvent } from "tone";
* const event = new ToneEvent();
2019-07-23 17:15:04 +00:00
* event.humanize = true;
*/
get humanize(): Time | boolean {
return this._humanize;
}
set humanize(variation) {
this._humanize = variation;
}
/**
2019-09-14 20:39:18 +00:00
* Start the note at the given time.
* @param time When the event should start.
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
start(time?: TransportTime | TransportTimeClass): this {
const ticks = this.toTicks(time);
if (this._state.getValueAtTime(ticks) === "stopped") {
2019-07-23 17:15:04 +00:00
this._state.add({
2019-09-14 22:12:44 +00:00
id: -1,
state: "started",
time: ticks,
2019-07-23 17:15:04 +00:00
});
this._rescheduleEvents(ticks);
2019-07-23 17:15:04 +00:00
}
return this;
}
/**
2019-09-14 20:39:18 +00:00
* Stop the Event at the given time.
* @param time When the event should stop.
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
stop(time?: TransportTime | TransportTimeClass): this {
2019-07-23 17:15:04 +00:00
this.cancel(time);
const ticks = this.toTicks(time);
if (this._state.getValueAtTime(ticks) === "started") {
this._state.setStateAtTime("stopped", ticks, { id: -1 });
const previousEvent = this._state.getBefore(ticks);
let reschedulTime = ticks;
2019-07-23 17:15:04 +00:00
if (previousEvent !== null) {
reschedulTime = previousEvent.time;
}
this._rescheduleEvents(reschedulTime);
}
return this;
}
/**
2019-09-14 20:39:18 +00:00
* Cancel all scheduled events greater than or equal to the given time
* @param time The time after which events will be cancel.
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
cancel(time?: TransportTime | TransportTimeClass): this {
2019-07-23 17:15:04 +00:00
time = defaultArg(time, -Infinity);
const ticks = this.toTicks(time);
this._state.forEachFrom(ticks, event => {
this.context.transport.clear(event.id);
2019-07-23 17:15:04 +00:00
});
this._state.cancel(ticks);
2019-07-23 17:15:04 +00:00
return this;
}
/**
2019-09-14 20:39:18 +00:00
* The callback function invoker. Also
* checks if the Event is done playing
* @param time The time of the event in seconds
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
protected _tick(time: Seconds): void {
2019-07-23 17:15:04 +00:00
const ticks = this.context.transport.getTicksAtTime(time);
if (!this.mute && this._state.getValueAtTime(ticks) === "started") {
if (this.probability < 1 && Math.random() > this.probability) {
return;
}
if (this.humanize) {
let variation = 0.02;
if (!isBoolean(this.humanize)) {
variation = this.toSeconds(this.humanize);
}
time += (Math.random() * 2 - 1) * variation;
}
this.callback(time, this.value);
}
}
/**
2019-09-14 20:39:18 +00:00
* Get the duration of the loop.
2019-07-23 17:15:04 +00:00
*/
2019-07-23 19:17:45 +00:00
protected _getLoopDuration(): Ticks {
2019-07-23 17:15:04 +00:00
return Math.round((this._loopEnd - this._loopStart) / this._playbackRate);
}
/**
2019-09-14 20:39:18 +00:00
* If the note should loop or not
* between ToneEvent.loopStart and
* ToneEvent.loopEnd. If set to true,
* the event will loop indefinitely,
* if set to a number greater than 1
* it will play a specific number of
* times, if set to false, 0 or 1, the
* part will only play once.
2019-07-23 17:15:04 +00:00
*/
get loop(): boolean | number {
return this._loop;
}
set loop(loop) {
this._loop = loop;
this._rescheduleEvents();
}
/**
2019-09-14 20:39:18 +00:00
* The playback rate of the note. Defaults to 1.
* @example
2019-10-24 22:01:27 +00:00
* import { ToneEvent } from "tone";
* const note = new ToneEvent();
2019-07-23 17:15:04 +00:00
* note.loop = true;
2019-10-24 22:01:27 +00:00
* // repeat the note twice as fast
2019-07-23 17:15:04 +00:00
* note.playbackRate = 2;
*/
get playbackRate(): Positive {
return this._playbackRate;
}
set playbackRate(rate) {
this._playbackRate = rate;
this._rescheduleEvents();
}
/**
2019-09-14 20:39:18 +00:00
* The loopEnd point is the time the event will loop
* if ToneEvent.loop is true.
2019-07-23 17:15:04 +00:00
*/
get loopEnd(): Time {
return new TicksClass(this.context, this._loopEnd).toSeconds();
}
set loopEnd(loopEnd) {
this._loopEnd = this.toTicks(loopEnd);
if (this._loop) {
this._rescheduleEvents();
}
}
/**
2019-09-14 20:39:18 +00:00
* The time when the loop should start.
2019-07-23 17:15:04 +00:00
*/
get loopStart(): Time {
return new TicksClass(this.context, this._loopStart).toSeconds();
}
set loopStart(loopStart) {
this._loopStart = this.toTicks(loopStart);
if (this._loop) {
this._rescheduleEvents();
}
}
/**
2019-09-14 20:39:18 +00:00
* The current progress of the loop interval.
* Returns 0 if the event is not started yet or
* it is not set to loop.
2019-07-23 17:15:04 +00:00
*/
get progress(): NormalRange {
if (this._loop) {
const ticks = this.context.transport.ticks;
const lastEvent = this._state.get(ticks);
if (lastEvent !== null && lastEvent.state === "started") {
const loopDuration = this._getLoopDuration();
const progress = (ticks - lastEvent.time) % loopDuration;
return progress / loopDuration;
} else {
return 0;
}
} else {
return 0;
}
}
dispose(): this {
super.dispose();
this.cancel();
this._state.dispose();
return this;
}
}