HTML and CSS Reference
In-Depth Information
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
false
});
soundPool
.
push
({
name
:
"explode1"
,
element
:
explodeSound2
,
played
:
false
false
});
soundPool
.
push
({
name
:
"explode1"
,
element
:
explodeSound3
,
played
:
false
false
});
soundPool
.
push
({
name
:
"shoot1"
,
element
:
shootSound
,
played
:
false
false
});
soundPool
.
push
({
name
:
"shoot1"
,
element
:
shootSound2
,
played
:
false
false
});
soundPool
.
push
({
name
:
"shoot1"
,
element
:
shootSound3
,
played
:
false
false
});
Nowweneedtomakeachangeinour
resetApp()
function.Thischangeistosupportsounds
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:
function
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
object has ended (
tSound.element.ended
) or whether
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
function
playSound
(
sound
,
volume
) {
var
var
soundFound
=
false
false
;
var
var
soundIndex
=
0
;
var
var
tempSound
;
iif
(
soundPool
.
length
>
0
) {
while
while
(
!
soundFound
&&
soundIndex
<
soundPool
.
length
) {
var
var
tSound
=
soundPool
[
soundIndex
];