HTML and CSS Reference
In-Depth Information
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,
becausetheonlyimplementation (atthetimeofthiswriting)isinGoogleChrome,weneedto
use its object for AudioContext , which is webkitAudioContext . (In theory, this should also
work in Safari, but our tests were not successful.)
var
var audioContext = new
new webkitAudioContext ();
Nextwewillsetupacouplevariablestoholdthesoundbuffersforourtwosounds(shootand
explode):
var
var shootSoundBuffer ;
var
var explodeSoundBuffer ;
Nowweneedtoloadeachsound.Tomakethingsstraightforward,wewillcreateafunctionto
load each soundthat accepts oneparameter,named url ,that represents the location andname
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
needstodoiscreateaninstanceof XMLHttpRequest() andconfigureitforbinarydata.Wedo
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 onload callback to an inline anonymous function. We will use this to
create a buffer for the sound it has loaded. In that function, we call audioCon-
text.decodeAudioData() to retrieve the binary loaded data as an audio buffer that we can
reference. That method requires three parameters:
1. The audio data ( request.response from the call to XMLHttpRequest )
2. A Success callback (another inline anonymous function that we will describe next)
3. A Failure callback function named onSoundError()
The success callback function receives an argument containing the buffer of the loaded
audio data. Weset ourvariable named shootSoundBuffer tothis argument, andweare ready
Search WWH ::




Custom Search