HTML and CSS Reference
In-Depth Information
shootSound.setAttribute("src", "shoot1." + audioType);
shootSound.addEventListener("canplaythrough",itemLoaded,false);
shootSound2 = document.createElement("audio");
document.body.appendChild(shootSound2);
shootSound2.setAttribute("src", "shoot1." + audioType);
shootSound2.addEventListener("canplaythrough",itemLoaded,false);
shootSound3 = document.createElement("audio");
document.body.appendChild(shootSound3);
shootSound3.setAttribute("src", "shoot1." + audioType);
shootSound3.addEventListener("canplaythrough",itemLoaded,false);
In the
itemLoaded()
function, we remove the event listeners for all six loaded sounds:
shootSound.removeEventListener("canplaythrough",itemLoaded, false);
shootSound2.removeEventListener("canplaythrough",itemLoaded, false);
shootSound3.removeEventListener("canplaythrough",itemLoaded, false);
explodeSound.removeEventListener("canplaythrough",itemLoaded,false);
explodeSound2.removeEventListener("canplaythrough",itemLoaded,false);
explodeSound3.removeEventListener("canplaythrough",itemLoaded,false);
Then, we push each sound into our
soundPool
array. However, this time, we push them
as dynamic objects so we can set the following properties, which don't exist in the
HTMLAudioElement
object:
name
The name of the sound file to play (again, without the extension).
element
The reference to the
HTMLAudioElement
object.
played
A Boolean that tells us whether this sound has played once or not. We need this
property because we are putting all of these
sound
objects into our array, but they
have not been played yet. That means their
ended
property has not yet been set to
true
. The
played
property tells us whether the sound is ready to play—that is, it
has not been played yet. We will set this to
true
after we play the sound once:
soundPool.push({name:"explode1", element:explodeSound, played:false});
soundPool.push({name:"explode1", element:explodeSound2, played:false});
soundPool.push({name:"explode1", element:explodeSound3, played:false});
soundPool.push({name:"shoot1", element:shootSound, played:false});
soundPool.push({name:"shoot1", element:shootSound2, played:false});
soundPool.push({name:"shoot1", element:shootSound3, played:false});
Now we need to make a change in our
resetApp()
function. This change is to support
sounds playing in Chrome, which appears to be the only browser that has a slight issue
with loading sounds in this manner. The first time you play a sound in Chrome, there
is a pause before it starts. To alleviate this, we play each sound type once but set the
volume to
0
. This will make sure a sound is loaded and ready to play the first time we
call
playSound()
in Chrome: