HTML and CSS Reference
In-Depth Information
function resetApp() {
playSound(SOUND_EXPLODE,0);
playSound(SOUND_SHOOT,0);
startLevel();
appState = STATE_PLAYING;
}
The playSound() function operates in a similar way to iteration #3. It loops through
the soundPool array looking for a sound that it can play. However, in this version, we
check to see whether the HTMLAudioElement has ended ( tSound.element.ended ) or if it
has not been played ( !tSound.played ) yet. We also check whether the value in the
sound parameter matches the name property of the sound object in soundPool
( tSound.name == sound ):
function playSound(sound,volume) {
var soundFound = false;
var soundIndex = 0;
var tempSound;
if (soundPool.length > 0) {
while (!soundFound && soundIndex < soundPool.length) {
var tSound = soundPool[soundIndex];
if ((tSound.element.ended || !tSound.played) && tSound.name == sound) {
soundFound = true;
tSound.played = true;
} else {
soundIndex++;
}
}
}
Using this method, we play a sound only if it has not been played, it has ended, and it
already has the sound file loaded that we need to play. There is no pause to load (most
of the time), and sounds play at pretty much the time we need them to play. If we need
more sounds, we can load more up front, or set MAX_SOUNDS to a number greater than
the number of preloaded sounds. If we do that, we will create new sound objects on the
fly (although this might still give you a pause when loading from a web server):
if (soundFound) {
tempSound = soundPool[soundIndex].element;
tempSound.volume = volume;
tempSound.play();
} else if (soundPool.length < MAX_SOUNDS){
tempSound = document.createElement("audio");
tempSound.setAttribute("src", sound + "." + audioType);
Search WWH ::




Custom Search