从我的基本理解来看,JavaScript 音频可视化器是根据实际声波反映音乐的。我想构建像节拍器(http://bl.ocks.org/1399233)这样的东西,我每隔一段时间就为一些 DOM 元素设置动画x
beats.
我现在这样做的方式是我手动计算出歌曲的节奏,假设它是 120bpm,然后我将其转换为毫秒来运行setInterval
打回来。但这似乎不起作用,因为浏览器性能导致它不精确。有没有更好的方法来确保回调完全按照歌曲的节奏执行?
如果没有,还有哪些其他策略可以将 JavaScript 动画与非音频可视化工具的歌曲节奏同步?
更新:看起来像这样吗?https://github.com/bestiejs/benchmark.js/blob/master/benchmark.js#L1606 https://github.com/bestiejs/benchmark.js/blob/master/benchmark.js#L1606
我有一个类似的问题,在那setInterval
不能依赖它来长期“保持时间”。我的解决方案是下面的代码片段:(在咖啡脚本中,编译后的js位于末尾的链接中)
它提供了 setInetrval 的替代品,它将非常接近于保持时间。有了它,您可以执行以下操作:
accurateInterval(1000 * 60 / bpm, callbackFunc);
请参阅我的用例和示例,将视觉效果与提供的 BPM 同步到 YouTube 视频:
准确间隔代码:
# 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
在这里获取咖啡脚本和js:https://gist.github.com/1d99b3cd81d610ac7351 https://gist.github.com/1d99b3cd81d610ac7351
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)