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 first adjust our game framework to allow the loading and updating of audio files. 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.
This task will be one of the shortest within the book 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.
We begin by loading the required audio file 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();
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'sUpdate
function.if(this.BoundingBox().Intersects(player.BoundingBox())) { this.DisposePickup(); effect.play(); }
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 file is loaded into the audio object by specifying a path to an external file, in this case, a .wav
file. This file is then loaded into the application through means of the HTML5 Audio API's Load
function. This function is used to load the audio file 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 file.