2013-04-17 55 views
0

我有一个获取音频的脚本。我想把这个频率与歌曲的确切时间联系起来。我可以获得webkitAudioContext currentTime属性,但这不准确,因为它在开始播放歌曲之前将声音保存在缓冲区中时开始计算时间。 这是我的代码:网络音频Api:与经过时间相关的频率

var context = new webkitAudioContext(); 

...

function drawSpectrogram(array) { 
    // copy the current canvas onto the temp canvas 
    var canvas = document.getElementById("canvas"); 

    tempCtx.drawImage(canvas, 0, 0, 800, 512); 
    // iterate over the elements from the array 
    for (var i = 0; i < array.length; i++) { 
     // draw each pixel with the specific color 
     var value = array[i]; 
     frequency = frequency + value + ";"; 
     time = time + Math.round((context.currentTime) * 1000000)/1000000 + ";";    
     ctx.fillStyle = hot.getColor(value).hex(); 
     // draw the line at the right side of the canvas 
     ctx.fillRect(800 - 1, 512 - i, 1, 1); 
    } 

}

谢谢!

回答

1

在准备好开始播放之前保存currentTime的值,并将该时间值用作“零时间”标记。无论何时您想知道音乐播放了多长时间,请从currentTime值中减去该时间值(表示设置需要多长时间)。

var context = new webkitAudioContext(); 

// load media, place in buffer, etc... 

var startTime = context.currentTime; // everything up to now has been setup 

// begin playing... 

var currentPlayingTime = context.currentTime - startTime; 

只需使用context.currentTime - startTime即可查找歌曲实际播放的时间。

1

我不太清楚你要什么,但你可能想看看高分辨率时间API:http://www.w3.org/TR/hr-time/

你可以抢在你打电话的同时当前时间.noteOn()或.start()放在您感兴趣的缓冲区中,然后在DrawSpectrogram函数中确定所需的时间。