Web Audio API and mobile browsers
- by Michael
I've run into a problem while implementing sound and music into an HTML game that I'm building. I'm using the Web Audio API, loading all the sound files with XMLHttpRequests and decoding them into an AudioBufferSourceNode with AudioContext.prototype.decodeAudioData(). It looks something like this:
var request = new XMLHttpRequest();
request.open("GET", "soundfile.ogg", true);
request.responseType = "arraybuffer";
request.onload = function() {
context.decodeAudioData(request.response)
}
request.send();
Everything plays fine, but on mobile the decodeAudioData takes an absurdly long time for the background music. I then tried using AudioContext.prototype.createMediaElementSource() to load the music from an HTML Audio object, since they support streaming and don't have to load the whole file into memory at once. It looked something like this:
var audio = new Audio('soundfile.ogg');
var source = context.createMediaElementSource(audio);
var mainVolume = context.createGain();
source.connect(mainVolume);
mainVolume.connect(context.destination);
This loads much faster, but the audio volume isn't affected by the gain node. Works fine on desktop, so I'm assuming this is a bug/limitation of mobile Chrome (testing on Android).
Is there actually no good, well-performing way to handle sound on mobile browsers or am just I doing something stupid?