根据我的基本理解,JavaScript音频可视化器根据实际声波反射音乐。我想构建类似节拍器的东西(http://bl.ocks.org/1399233),我在每个x
节拍中为一些DOM元素设置动画。
我现在这样做的方法是手动找出歌曲的速度,说它是120bpm,然后我将其转换为毫秒来运行setInterval
回调。但这似乎不起作用,因为浏览器性能导致它不精确。有没有更好的方法来确保回调的执行完全与歌曲所处的相同速度?
如果没有,有哪些其他策略可以将JavaScript动画与歌曲的节奏同步,而不是音频可视化工具?
更新:看起来像这样的东西? https://github.com/bestiejs/benchmark.js/blob/master/benchmark.js#L1606
答案 0 :(得分:6)
我遇到了类似的问题,因为setInterval
无法长期依赖“保持时间”。我的解决方案是下面的代码段:(在咖啡脚本中,编译的js在最后的链接中)
它为setInetrval提供了一个替代品,它将保持非常接近于保持时间。有了它,你可以这样做:
accurateInterval(1000 * 60 / bpm, callbackFunc);
请参阅我的用例和示例,它将视觉效果与提供的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
答案 1 :(得分:2)
这篇文章可能有用:
要点是你在setInterval()
中运行的功能比你的速度略快,例如,每100毫秒。很长一点,您可以通过检查(new Date()).getMilliseconds()
的值来查看是否是时间播放“节拍”,并查看是否已经过了一个节拍的等效时间而不是依赖于不那么准确setTimeout
或setInterval
个函数。
即使这样,音乐本身,除非由计算机生成,可能没有完美或一致的节奏,因此对于不合时宜的节拍来说可能是一个障碍,这可能是为什么使用音频分析找到实际节拍的位置即将发生可能是一条更好的路线。