HTML and CSS Reference
In-Depth Information
We also need to create an array to hold our pool of sounds:
var
var
soundPool
=
new
new
Array
();
To control which sound we want to play, we assign a constant string to each, and to play the
sound, we just need to use the constant. This way, we can change the sound names easily,
which will help in refactoring code if we want to modify the sounds later:
var
var
SOUND_EXPLODE
=
"explode1"
;
var
var
SOUND_SHOOT
=
"shoot1"
;
var
var
SOUND_SAUCER_SHOOT
=
"saucershoot"
Finally,weneedan
audioType
variable,whichweusetoreferencethecurrentfiletype(
.ogg
,
.mp3
, or
.wav
) by the sound manager code.
Loading in sounds and tile sheet assets
an idle state. We add this code to our game in a
gameStateInit()
function.
NOTE
Sounddoesnotworkthesameinallbrowsers.Inthisexamplegame,wearepreloadingalltheimages
andsounds.ForInternetExplorer9and10,thispreloadingsometimesdoesnotwork.Youcanchange
the number of items to preload from 16 to 7 to test the game without sound in Internet Explorer
browsers that have trouble with the preloading.
function
function
gameStateInit
() {
loadCount
=
0
;
itemsToLoad
=
16
;
// change to 7 for IE
explodeSound
=
document
.
createElement
(
"audio"
);
document
.
body
.
appendChild
(
explodeSound
);
audioType
=
supportedAudioFormat
(
explodeSound
);
explodeSound
.
setAttribute
(
"src"
,
"explode1."
+
audioType
);
explodeSound
.
addEventListener
(
"canplaythrough"
,
itemLoaded
,
false
false
);
explodeSound2
=
document
.
createElement
(
"audio"
);
document
.
body
.
appendChild
(
explodeSound2
);
explodeSound2
.
setAttribute
(
"src"
,
"explode1."
+
audioType
);
explodeSound2
.
addEventListener
(
"canplaythrough"
,
itemLoaded
,
false
false
);
explodeSound3
=
document
.
createElement
(
"audio"
);
document
.
body
.
appendChild
(
explodeSound3
);
explodeSound3
.
setAttribute
(
"src"
,
"explode1."
+
audioType
);