Skip to content

Instantly share code, notes, and snippets.

@spite
Last active August 29, 2015 13:56
Show Gist options
  • Save spite/8835249 to your computer and use it in GitHub Desktop.
Save spite/8835249 to your computer and use it in GitHub Desktop.
AudioContext playback without preloading
/*
Demo here: http://www.clicktorelease.com/tmp/fastload/
The MP3 file is 5.2MB
*/
/*
For some reason, probably because the spec has changed since the article
"Getting Started with Web Audio API" in http://www.html5rocks.com/en/tutorials/webaudio/intro/
was published, the most common way of loading a file sound is something like:
*/
var oReq = new XMLHttpRequest();
oReq.open( 'GET', fileName, true);
oReq.responseType = 'arraybuffer';
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response;
// do arrayBuffery things, probably with AudioContext.context.decodeAudioData
};
oReq.send(null);
/*
Which forces the browser to download the file completely before starting decoding.
That's inconvenient because it's not necessary -AudioElement doesn't do that- and
because it makes loading process unecessarily long.
So it turns out this works:
*/
var context = new AudioContext();
var a = document.createElement( 'audio' );
a.src = trackName;
a.play();
var audioSource = context.createMediaElementSource( a );
audioSource.connect( context.destination );
/*
The browser will start playing almost right away.
You can connect all the nodes you want, it all works the same
Tested with Chrome, Firefox and Safari OSX; Chrome and Firefox Android.
Haven't tried iOS.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment