2011-11-23 28 views
2

任務是模擬js中的MIDI播放器工作,但僅用於模擬節拍之間的延遲。存在與節拍時鐘格式節拍開始時間的陣列,例如[960,1280,2200,...],和式我使用計算毫秒時間針對每個節拍蜱:在Javascript中模擬MIDI節拍時鐘

var beatTickTime = 60000/(tempo * 96); 

問題在於非常緩慢的實時生成。即使我使用1秒延遲,它仍然非常慢。下面是它是如何實現的:

var tickTimer = setInterval(function() { 
    ... 
    tickCount += 1; 
}, beatTickTime); // or just 1 ms 

我應該通過一些意想不到蜱做tickCount += someNumber?或者有更常見的方法來解決這個問題?另外我不確定96式(PPQ * 4次)在我的公式中。

P. S.拍蜱來自解析的吉他親文件

回答

2

有沒有保證,當你問它setInterval()將運行速度極快。即使超時設置爲1,也不能指望每秒鐘調用1,000次的函數。

你很可能需要做類似如下:

var startTime = (new Date()).getTime(); 
setInterval(function() { 
    var relTime = (new Date()).getTime() - startTime; 
    // relTime is now the number of ms since the script started 

    /* 
    In here, you'll need to see if relTime is large enough to indicate the next 
    beat has been reached. So that means keeping some sort of external marker 
    to indicate the most recent beat that has occurred -- when relTime is big 
    enough to move that marker to the next beat, also run any code that is 
    necessary to handle that beat. 
    */ 
}, 1); 

循環運行「儘可能快,因爲它可以」,但仍速度遠遠慢於期望。它測量相對於腳本開始的當前時間,並確定每次迭代的差異。你可以將這段時間除以歌曲的節奏,並且你會有一個指示你當前歌曲的位置。

+2

這是一個很好的嘗試,但很可能無濟於事,因爲日期時間仍然與受諸如調整大小事件和垃圾回收等因素影響的瀏覽器主線程有關,更不用說它只是具有毫秒精度。解決此問題的新方法是使用帶有調度的Web音頻時鐘,如以下詳細描述:http://www.html5rocks.com/en/tutorials/audio/scheduling/ – starmandeluxe