HTML and CSS Reference
In-Depth Information
to play the sound in the game. We then call itemLoaded() so that we can increment the
loadCount variable in the Space Raiders game.
function loadShootSound ( url ) {
var request = new
new XMLHttpRequest ();
request . open ( 'GET' , url , true
true );
request . responseType = 'arraybuffer' ;
request . onload = function
function () {
audioContext . decodeAudioData ( request . response , function
function ( buffer ) {
shootSoundBuffer = buffer ;
itemLoaded ();
}, onSoundError );
request . send ();
function onSoundError ( e ) {
alert ( "error loading sound" )
We then create a similar function like the above for the “explode” sound. The only difference
isthatweset explodeSoundBuffer tothevalueofthebufferinthesuccesscallbackfunction:
explodeSoundBuffer = buffer ;
Now, inside the game when we want to play a sound, we call the playSound() function,
passing the name of the sound buffer we want to play:
playSound ( shootSoundBuffer );
The playSound() function is now totally different than the one we created in the previous
iteration of Space Raiders because we don't have to manage multiple copies of each sound.
First, we create an instance of AudioBufferSourceNode by calling audioCon-
text.createBufferSource() and save it in a variable named source . This object will hold
the sound that we will be playing. We set the buffer property of source to the buffer that
we passed into the function. Again, this buffer represents one ofoursoundsin memory (shoot
or explode). We then call the connect function of audioContext to set the destination for
the sound. For our purposes, we are using the default destination value, which should be the
speakers on your computer. Finally, we call the noteOn() function of the source, passing 0 ,
which means “start playing immediately.”
You can call the noteOn() function on an instance of AudioBufferSourceNode only once.
After that, it will never play a second time. You need to create another instance if you want
Search WWH ::

Custom Search