HTML and CSS Reference
In-Depth Information
Adding sounds (Must know)
As another form of emersion within the game, we will look at introducing sound effects to
the game. However, in order to implement sound we must irst adjust our game framework
to allow the loading and updating of audio iles. In order to do this, we will take advantage of
the HTML5 Audio API, which is compatible with the latest versions of each of the major web
browsers such as Google Chrome, Internet Explorer, Firefox, and Opera.
How to do it...
This task will be one of the shortest within the topic as most of the functionality required
to load and buffer audio within our game will be provided by the HTML5 Audio API, which is
compatible with each of the major web browsers.
1. We begin by loading the required audio ile into the application by placing the
following code inside of the Main object after we load in each of the game textures:
var effect = new Audio("audio/sound.wav");
effect.load();
2.
The next step involves playing the audio, in this case, we will tell the audio to play
when the player has collided with a pickup. This is done by placing the following code
inside of the collision detection check within the Pickup object's Update function.
if(this.BoundingBox().Intersects(player.BoundingBox())) {
this.DisposePickup();
effect.play();
}
How it works...
We begin by creating a new audio object, which holds the audio effect that is played when the
player collides with a pickup. The audio ile is loaded into the audio object by specifying a path
to an external ile, in this case, a .wav ile. This ile is then loaded into the application through
means of the HTML5 Audio API's Load function. This function is used to load the audio ile
into the application prior to the canvas being drawn so that it is available when we begin to
play the game.
In order for the sound effect to play when we collide with a pickup, we make use of yet another
HTML5 Audio function known as Play . This function is responsible for buffering and playing
the audio ile.
 
Search WWH ::




Custom Search