Reputation: 35
I have a script that gets audio frequencies. I want to relate that frequency with the exact time of the song. I can get the webkitAudioContext currentTime property, but this is not accurate because it starts to count time when saving the sound in the buffer before the song starts. This is my code:
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);
}
}
Thank you!
Upvotes: 1
Views: 820
Reputation: 115950
Save the value of currentTime
just before you are ready to begin playing, and use that time value as your "zero-time" marker. Whenever you want to know how long the music has been playing, subtract that time value (which indicates how long setup took) from the currentTime
value.
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;
Just use context.currentTime - startTime
to find how long the song has actually been playing.
Upvotes: 2
Reputation: 146
I'm not quite sure what you're going for, but you might want to take a look at the High Resolution Time API: http://www.w3.org/TR/hr-time/
You could grab the current time at the same time that you call .noteOn() or .start() on the buffer you're interested in, and then in your DrawSpectrogram function determine the time elapsed to do what you need.
Upvotes: 1