在Javascript中模拟MIDI节拍时钟

时间:2011-11-23 16:11:02

标签: javascript time midi clock

任务是模拟js中的MIDI播放器工作,但仅用于模拟节拍之间的延迟。有一个节拍时钟格式的节拍开始时间,例如[960,1280,2200,...],以及我用于计算每个节拍时间的毫秒时间的公式:

var beatTickTime = 60000 / (tempo * 96);

问题在于实时生成非常慢。即使我使用1秒延迟,它仍然非常慢。以下是它的实施方式:

var tickTimer = setInterval(function() {
     ...
     tickCount += 1; 
}, beatTickTime); // or just 1 ms

我应该通过tickCount += someNumber传递一些节拍?或者有更常见的方法来解决这个问题?我也不确定我的公式中有96(PPQ * 4次)。

P上。 S. beat ticks来自解析的吉他专业文件

1 个答案:

答案 0 :(得分:2)

无法保证setInterval()的运行速度与您要求的速度一样快。即使超时设置为1,也不能指望每秒调用1000次的函数。

您很可能需要执行以下操作:

var startTime = (new Date()).getTime();
setInterval(function() {
  var relTime = (new Date()).getTime() - startTime;
  // relTime is now the number of ms since the script started

  /*
  In here, you'll need to see if relTime is large enough to indicate the next
  beat has been reached. So that means keeping some sort of external marker
  to indicate the most recent beat that has occurred -- when relTime is big
  enough to move that marker to the next beat, also run any code that is
  necessary to handle that beat.
  */
}, 1);

循环“尽可能快地”运行,但仍然比预期慢得多。它测量相对于脚本开始的当前时间,并确定每次迭代的差异。您可以按照歌曲的速度划分该时间,并且您将指示您当前所在歌曲的位置。