Web Audio Api:与经过时间相关的频率

时间:2013-04-17 09:43:07

标签: javascript google-chrome html5-audio web-audio

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

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);
    }

}

谢谢!

2 个答案:

答案 0 :(得分:1)

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

您可以在您感兴趣的缓冲区上调用.noteOn()或.start()的同时获取当前时间,然后在DrawSpectrogram函数中确定执行所需操作所用的时间。

答案 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查找歌曲实际播放的时长。