I cannot make work AnalayserNode with AudioContext.createMediaElementSource in mobile devices. It does not work in Safari on iOS and does not work in Chrome on Android. When I do analayser.getByteFrequencyData(buffer);
I always get an array with zeros. Is this a bug? where should I report it? Any workaround?
Full code below or in Codepen: http://codepen.io/elranu/pen/WQOerB
var initialized = false;
var audio = new Audio();
audio.src = "http://blogtalk.vo.llnwd.net/o23/show/6/884/show_6884921_2014_09_08_16_11_36.mp3";
audio.crossOrigin = "anonymous";
audio.preload = false;
function init(){
var context = new AudioContext();
var source = context.createMediaElementSource(audio);
var anal = context.createAnalyser();
anal.fftSize = 1024;
var buffer = new Uint8Array(anal.frequencyBinCount);
var lines = [];
var eq = document.getElementById('eq');
for(var index = 0; index < buffer.length; index++){
var line = document.createElement('div');
line.className = 'line';
lines.push(line);
eq.appendChild(line);
}
source.connect(anal);
anal.connect(context.destination);
setInterval(function(){
anal.getByteFrequencyData(buffer);
for(var index = 0; index < buffer.length; index++){
lines[index].style.height = buffer[index] + 'px';
}
}, 50);
}
function startAudio(){
if(!initialized){
init();
initialized = true;
}
audio.play();
}
function stopAudio(){
audio.pause();
}
.line {
width: 2px;
background-color: blue;
margin-left:3px;
display:inline-block;
}
#eq {
height: 500px;
}
<button onclick="startAudio()">Start Audio</button>
<button onclick="stopAudio()">Stop Audio</button>
<div id="eq">
</div>
Update: I have noticed that the AnalayserNode works on mobile if the source of the AudioContext is createBufferSource()
. But this is not a viable way to solve the problem. Because to create a buffer I have to do the following request:
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function(){//stufff...};
And if I do this request, the mobile device will download the full audio, just render the frequency of the audio. With big audios this is no viable solution in mobile, because the user could wait a lot just to start playing.
An example to test this: http://webaudioapi.com/samples/visualizer/
I found the answer, unfortunately is a bug. More information here: https://code.google.com/p/chromium/issues/detail?id=419446