Space Raiders with the Web Audio API Applied

We are now going to create another version of Space Raiders, this time using the Web Audio API. The first thing we need to do is to get a reference to the AudioContext object. However, because the only implementation (at the time of this writing) is in Google Chrome, we need to use its object for AudioContext, which is webkitAudioContext. (In theory, this should also work in Safari, but our tests were not successful.)

var audioContext = new webkitAudioContext();

Next we will set up a couple variables to hold the sound buffers for our two sounds (shoot and explode):

var shootSoundBuffer;
var explodeSoundBuffer;

Now we need to load each sound. To make things straightforward, we will create a function to load each sound that accepts one parameter, named url, that represents the location and name of the sound file. In the initApp() function, we will get the audioType value as before, but now it will also call our two new functions to load the sounds:

audioType = supportedAudioFormat(tempSound);
loadExplodeSound("explode1." + audioType);
loadShootSound("shoot1."+ audioType);

Next, we need to create the functions that will load the sounds. The first thing the function needs to do is create an instance of XMLHttpRequest()and configure it for binary data. We do this by setting the responseType of XMLHttpRequest to arraybuffer. This is a new way to load data with XMLHttpRequest that allows us to open binary files, such as audio files.

We then set the ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.