From my basic understanding, JavaScript audio visualizers are reflecting the music based on the actual sound waves. I would like to build something like a metronome (http://bl.
I had a similar problem, in that setInterval
could not be relied on to "keep time" over a long period. My solution was the snippet below: (in coffee script, compiled js is in the link at the end)
It provides a drop in replacement for setInetrval that will stay very close to keeping time. With it, you can do this:
accurateInterval(1000 * 60 / bpm, callbackFunc);
See my use case and example that syncs visuals with a provided BPM to a youtube video here: http://squeegy.github.com/MandalaTron/?bpm=64&vid=EaAzRm5MfY8&vidt=0.5&fullscreen=1
accurateInterval code:
# 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
get the coffee script and js here: https://gist.github.com/1d99b3cd81d610ac7351