So I've been playing around with audio visualization in Javascript. I have code that looks like this.
let audioElement = document.getElementById('source');
let audioCtx = new AudioContext();
let analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
let total_rects=analyser.fftSize/32;
let source = audioCtx.createMediaElementSource(audioElement);
source.connect(analyser);
source.connect(audioCtx.destination);
var data = new Uint8Array(analyser.frequencyBinCount);
Then I can run
analyser.getByteFrequencyData(data);
Which, while the audio is playing, will populate the variable "data" with an array representing frequency data of the audio for the current "frame", so to speak. What I want to be able to do is create an array of such data for every "frame". Or, alternatively, to select data arbitrarily based on timestamp. (In milliseconds, say.)
Currently I can do something like this:
let final_data=[];
let captureFunction=function() {
analyser.getByteFrequencyData(data);
final_data.push([...data]);
}
if(!audio_ended) {
window.requestAnimationFrame(captureFunction);
}
};
window.requestAnimationFrame(captureFunction);
This works reasonably well, but I can't technically guarantee the frequency or reliability of requestAnimationFrame firing. How might I accomplish what I'm trying to do?