2011-11-30 50 views
4

從我的基本理解來看,JavaScript音頻可視化器反映的是基於實際聲波的音樂。我想創建一個類似於節拍器的東西(http://bl.ocks.org/1399233),在那裏我每跳x跳動一些DOM元素。如何在不構建「音頻可視化器」的情況下將JavaScript動畫與歌曲的速度同步?

我現在這樣做的方式是手動計算出歌曲的節奏,比如說120bpm,然後我將其轉換爲毫秒來運行setInterval回調。但是這似乎不起作用,因爲瀏覽器性能導致它不精確。有沒有更好的方法確保回放的執行速度與歌曲的速度完全相同?

如果沒有,還有什麼其他策略可以將JavaScript動畫與不是音頻可視化器的歌曲節奏同步?

更新:它看起來像這樣的東西? https://github.com/bestiejs/benchmark.js/blob/master/benchmark.js#L1606

回答

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 

GET咖啡腳本和js在這裏:https://gist.github.com/1d99b3cd81d610ac7351

+0

雖然沒有真正回答這個問題。你或許可以準確地掌握節奏,但是由於音樂需要一些未知時間才能加載,所以你會在一段固定的時間內關閉;我不認爲有一個確定的方法可以知道音樂什麼時候開始播放。 –

2

此信息可能是相關的:

要點是,你運行你的setInterval()略快於你的節奏的功能,例如,每100毫秒。很簡單的例子,您可以通過檢查(new Date()).getMilliseconds()的值並查看是否已經通過一個毫秒的等值而不是依賴不太精確的setTimeoutsetInterval函數來跟蹤是否應該播放「節拍」 。即使如此,音樂本身(除非由計算機生成)可能沒有完美或一致的速度,因此考慮到誤操作的節拍可能是您的障礙,這可能是使用音頻分析來找到真實節拍的原因將要發生的可能是更好的路線。

相關問題