use phase to allow smooth tempo changes

This commit is contained in:
Felix Roos 2022-08-12 22:01:09 +02:00
parent ea1ffca4ae
commit c2354bffa2

View file

@ -9,21 +9,22 @@ import { ClockWorker } from './clockworker.mjs';
export class Scheduler { export class Scheduler {
worker; worker;
pattern; pattern;
startedAt; phase;
audioContext; audioContext;
cps = 1; cps = 1;
constructor({ audioContext, interval = 0.1, onEvent, latency = 0.1 }) { constructor({ audioContext, interval = 0.1, onEvent, latency = 0.1 }) {
this.audioContext = audioContext; this.audioContext = audioContext;
this.worker = new ClockWorker((tick, interval) => { this.worker = new ClockWorker((tick, interval) => {
const begin = tick * interval * this.cps; const begin = this.phase;
const end = (tick + 1) * interval * this.cps; const end = this.phase + interval * this.cps;
this.phase = end;
const haps = this.pattern.queryArc(begin, end); const haps = this.pattern.queryArc(begin, end);
haps.forEach((e) => { haps.forEach((e) => {
if (!e.part.begin.equals(e.whole.begin)) { if (!e.part.begin.equals(e.whole.begin)) {
return; return;
} }
if (e.context.onTrigger) { if (e.context.onTrigger) {
const ctxTime = e.whole.begin / this.cps + this.startedAt + latency; const ctxTime = (e.whole.begin - begin) / this.cps + this.audioContext.currentTime + latency;
e.context.onTrigger(ctxTime, e, this.audioContext.currentTime, this.cps); e.context.onTrigger(ctxTime, e, this.audioContext.currentTime, this.cps);
} }
if (onEvent) { if (onEvent) {
@ -37,7 +38,7 @@ export class Scheduler {
throw new Error('Scheduler: no pattern set! call .setPattern first.'); throw new Error('Scheduler: no pattern set! call .setPattern first.');
} }
this.audioContext.resume(); this.audioContext.resume();
this.startedAt = this.audioContext.currentTime; this.phase = 0;
this.worker.start(); this.worker.start();
} }
stop() { stop() {