Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML 5 Audio - AnalyserNode.getByteFrequencyData() Returns Undefined

This appears to be a common question - Javascript Web Audio API AnalyserNode Not Working - But I can't be sure if I've found an edge case with my implementation.

I create an audio source using createMediaElementSource(), but instead of using an audio tag from the page markup, the element is created dynamically using Buzz.js.

Here's my test setup:

window.addEventListener('load', function(e) {
    audioContext = new webkitAudioContext();
    audioAnalyser = audioContext.createAnalyser();

    sound = new buzz.sound("sound.mp3");
    sound.load().bind("canplaythrough", function(e) {
        source = audioContext.createMediaElementSource(this.sound);
        source.connect(audioAnalyser);

        audioAnalyser.connect(audioContext.destination);

        this.play().loop(); 
    });
}, false);

window.setInterval(function(){
    array = new Uint8Array(audioAnalyser.frequencyBinCount);
    console.log(audioAnalyser.getByteFrequencyData(array));                                           
})    

With the code above, the sound plays. I can also attach others nodes (biquad filters, gain etc) which work, but the audioAnalyser.getByteFrequencyData returns undefined values on every frame...

Might it have anything to do with using Buzz.js?

like image 262
Charlie Avatar asked Jan 12 '23 21:01

Charlie


1 Answers

It was a failure of comprehension...

Basically, I was expecting the console to log some kind of output from the following:

window.setInterval(
    array = new Uint8Array(audioAnalyser.frequencyBinCount);
    console.log(audioAnalyser.getByteFrequencyData(array));                                           
)

What I should have done was this:

window.setInterval(function(){
    array = new Uint8Array(audioAnalyser.frequencyBinCount);
    audioAnalyser.getByteFrequencyData(array); 
    console.log(array);                                 
})

A bit silly, but I hope that helps anyone coming here who might have expected getByteFrequencyData to return a value of somekind.

like image 60
Charlie Avatar answered Jan 28 '23 10:01

Charlie