Nourdine Alouane
Nourdine Alouane

Reputation: 814

Audio context not working properly on android

I'm having this issue with android (either for android browser or chrome for android): getByteFrequencyData method returns 0 values.

Some say that the Web Audio Api is not supported in android mobile devices (IOS does support it) but I have juste checked this link, where it says that chrome 49 support Audio Api.

Some say that it is an old issue

And some say that the problem comes from the media element, if you can load the media with XHR into a buffer and play it, it will work (I tested but it didn't work)

I'm trying to make an audio visualizer working on android cordova by using Audio APi + Canvas Any help?

Upvotes: 0

Views: 1338

Answers (1)

Nourdine Alouane
Nourdine Alouane

Reputation: 814

I got it to work, createBuffer() method with two arguments was not working on chrome versions anymore, so I had to use decodeAudioData in order to get the buffer source:

// Create AudioContext and buffer source
var audioCtx = new AudioContext();
source = audioCtx.createBufferSource();
// load in an audio track via XHR and decodeAudioData
function getData() {
request = new XMLHttpRequest();
request.open('GET', 'Test.mp3', true);
request.responseType = 'arraybuffer';
request.onload = function() {
var audioData = request.response;

audioCtx.decodeAudioData(audioData, function(buffer) {
myBuffer = buffer;   
source.buffer = myBuffer;

analyser = audioCtx.createAnalyser(); // AnalyserNode method
canvas = document.getElementById('CanvasDiv');
canvasContext = canvas.getContext('2d');
source.connect(analyser);
analyser.connect(audioCtx.destination);

frameLooper(); 
},
function(e){"Error with decoding audio data" + e.err});
}
request.send();
}
function frameLooper(){
ionic.requestAnimationFrame(frameLooper); //You can use window instead of ionic
fbc_array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fbc_array);
canvasContext.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
canvasContext.fillStyle = '#00CCFF'; // Color of the bars
bars = 100;

for (var i = 0; i < bars; i++) {
    bar_x = i * 3;
    bar_width = 2;
    bar_height = -(fbc_array[i] / 2);
    //  fillRect( x, y, width, height ) // Explanation of the parameters below
    canvasContext.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
}
getData();
var audio = document.getElementById('audioTagId');
Callback = function(){
        source.start();
    }
document.getElementById("PlayButton").addEventListener("click", Callback);

Upvotes: 1

Related Questions