如何在不构建"音频可视化器"的情况下将JavaScript动画与歌曲的速度同步?

Lan*_*ard 4 javascript audio animation

根据我的基本理解,JavaScript音频可视化器根据实际声波反射音乐.我想构建类似节拍器(http://bl.ocks.org/1399233)的东西,在那里我为每个x节拍动画一些DOM元素.

我现在这样做的方式是我手动找出歌曲的速度,说它是120bpm,然后我将其转换为毫秒来运行setInterval回调.但这似乎不起作用,因为浏览器性能导致它不精确.有没有更好的方法来确保回调是在歌曲所处的相同速度下完全执行的?

如果没有,还有哪些其他策略可以将JavaScript动画与歌曲的节奏同步,而不是音频可视化器?

更新:看起来像这样的东西? https://github.com/bestiejs/benchmark.js/blob/master/benchmark.js#L1606

Ale*_*yne 6

我有一个类似的问题,因为setInterval在很长一段时间内不能依靠"保持时间".我的解决方案是下面的代码片段:(在咖啡脚本中,编译的js在最后的链接中)

它为setInetrval提供了一个替代品,它将保持非常接近于保持时间.有了它,你可以这样做:

accurateInterval(1000 * 60 / bpm, callbackFunc);
Run Code Online (Sandbox Code Playgroud)

请参阅我的用例和示例,它将视觉效果与提供的BPM同步到youtube视频:http://squeegy.github.com/MandalaTron/?bpm = 64&vid = EaAzRm5MfY8&vidt = 0.5 &fullscreen = 1

accurateInterval代码:

# Accurate Interval, guaranteed not to drift!
# (Though each call can still be a few milliseconds late)
window.accurateInterval = (time, fn) ->

  # This value is the next time the the timer should fire.
  nextAt = new Date().getTime() + time

  # Allow arguments to be passed in in either order.
  if typeof time is 'function'
    [fn, time] = [time, fn]

  # Create a function that wraps our function to run.  This is responsible for
  # scheduling the next call and aborting when canceled.
  wrapper = ->
    nextAt += time
    wrapper.timeout = setTimeout wrapper, nextAt - new Date().getTime()
    fn()

  # Clear the next call when canceled.
  wrapper.cancel = -> clearTimeout wrapper.timeout

  # Schedule the first call.
  setTimeout wrapper, nextAt - new Date().getTime()

  # Return the wrapper function so cancel() can later be called on it.
  return wrapper
Run Code Online (Sandbox Code Playgroud)

在这里获取咖啡脚本和js:https://gist.github.com/1d99b3cd81d610ac7351