Buffer and play a sound in Web Audio

Press the space bar to play,
or click this button.


By loading sound into a RAM buffer, we gain immediate random access to the data, giving optimal control over its use. This process is a little more complicated than just using an Audio element (just playing a sound file), but it's usually preferable because of the versatility it provides. The buffered sound can be treated as a source audio node, similar to an oscillator, and can thus be played, processed, analyzed, drawn, etc.

You use the XMLHttpRequest API to get data from a sound file on the server, place that data in an AudioBuffer, decode it if it's in a compressed format such as MP3, then use that buffer of decoded audio as a BufferSourceNode in the audio context. For simplicity, this example does nothing more than that, then connects the BufferSourceNode to the context destination and starts it.