防止 BPM 自动收报机缓慢漂移与真实节拍器不同步

Preventing a BPM ticker from slowly drifting out of sync with a real metronome

我正在开发一个将 BPM 值作为输入的音乐生成器,之后它将开始生成一些和弦、低音音符,并使用 MIDI 信号触发鼓 VSTi。

为了让所有 运行ning 保持正确的每分钟节拍数,我使用了一个挂钟计时器,它在您点击播放时从 0 开始计时,然后开始计数 1/第 128 个音符为 "ticks",有规律地间隔。每次函数滴答结束时,我都会通过简单地计算适合自开始时间的滴答数来检查未来有多少滴答声:

class TrackManager {
  constructor(BPM) {
    this.tracks = ... 
    this.v128 = 60000/(BPM*32);
  }

  ...

  play() {
    this.tickCount = 0;
    this.playing = true;
    this.start = Date.now();
    this.tick();
  }

  tick() {
    if (!this.playing) return;

    // Compute the number of ticks that fit in the
    // amount of time passed since we started
    let diff = Date.now() - this.start;
    let tickCount = this.tickCount = (diff/this.v128)|0;

    // Inform each track that there is a tick update,
    // and then schedule the next tick.
    this.tracks.forEach(t => t.tick(this.tickCount));
    setTimeout(() => this.tick(), 2);
  }

  ...
}

曲目根据 Steps 生成音乐,这些音乐以节拍表示它们的预期播放长度(使用 .duration 作为持久长度指示器,.end 设置为播放一个步骤时的未来滴答值),回放代码添加了对播放一个步骤的滴答数的校正,以确保如果通过的滴答数多于预期(例如由于复合舍入错误),则下一步播放但需要更少的滴答声,以保持同步。

class Track {
  ...

  tick(tickCount) {
    if (this.step.end <= tickCount) {
      this.playProgramStep(tickCount);
    }
  }

  playProgramStep(tickCount) {
    // Ticks are guaranteed monotonically increasing,
    // but not guaranteed to be sequential, so if we
    // find a gap of N ticks, we need to correct the
    // play length of the next step by that many ticks:
    let correction = this.stopPreviousStep(tickCount);
    let step = this.setNextStep();
    if (step) {
      step.end = tickCount + step.duration - correction;
      this.playStep(step);
    }
  }

  stopPreviousStep(tickCount) {
    this.step.stop();
    return (tickCount - this.step.end);
  }

  ...
}

这工作得相当好,但最终的音轨速度仍然存在一些漂移,当 运行使用单独的节拍器(在我的例子中,鼓模式 VSTi,它被告知哪个模式以哪个 BPM 播放,然后留给自己做自己的事情)。虽然最初听起来还不错,但大约一分钟后,节拍器播放的 BPM 与发生器 运行 的 BPM 之间出现轻微但明显的不同步,我不确定这种不同步可能在哪里仍然来自。

我本以为滴答级别的不同步最微妙(对于 120 BPM 小于 16 毫秒),这远低于明显的水平,但代码中似乎存在复合不同步,我是不确定它会在哪里。滴答声是根据系统时钟生成的,所以我不希望在 JS 运行 进入 Date.now() 的不稳定整数值之前出现不同步,我们不会 运行 再过 285 年左右

什么可能仍然导致不同步?

事实证明,this.v128 的计算仍然会导致引入漂移的值。例如,120 BPM 每节拍产生 15.625 毫秒,这是相当可靠的,但 118 BPM 每节拍产生 15.889830508474576271186440677966[...] 毫秒,任何四舍五入(到任何数量的有效数字)最终都会产生越来越不正确的结果tickCount计算。

这里的解决方案是通过将 this.v128 值替换为 this.tickFactor = BPM * 32; 然后更改 tick() 函数来计算 tickCount 为:

tick() {
  if (!this.playing) return;

  // Compute the number of ticks that fit in the
  // amount of time passed since we started
  let diff = Date.now() - this.start;

  // first form a large integer, which JS can cope with just fine,
  // and only use division as the final operation.
  let tickCount = this.tickCount = ((diff*this.tickFactor)/60000)|0;

  // Inform each track that there is a tick update,
  // and then schedule the next tick.
  this.tracks.forEach(t => t.tick(this.tickCount));
  setTimeout(() => this.tick(), 2);
}