Adding Sound

In Chapter 7, we covered everything we need to know to add robust sound management to our canvas applications. If you are unfamiliar with the concepts presented in Chapter 7, please review that chapter first. In this chapter, we cover only the code necessary to include sound in our game.

Arcade games need to play many sounds simultaneously, and sometimes those sounds play very rapidly in succession. In Chapter 7, we used the HTML5 <audio> tag to create a pool of sounds, solving the problems associated with playing the same sound instance multiple times.

Note

As of this writing, the Opera browser in Windows offers the best support for playing sounds. If you are having trouble with the sound in this game, any other sound example in the book, or in your own games, please test them in the Opera browser.

The sounds for our game

We add three sounds to our game:

  • A sound for when the player shoots a projectile (shoot1.mp3, .ogg, .wav)

  • A sound for explosions (explode1.mp3, .ogg, .wav)

  • A sound for when the saucer shoots a projectile (saucershoot.mp3, .ogg, .wav)

In the file download for this chapter, we have provided each of the three sounds in three formats: .wav, .ogg, and .mp3.

Adding sound instances and management variables to the game

In the variable definition section of our game code, we create variables to work with the sound manager code from Chapter 7. We create three instances of each sound that goes into our pool:

var explodeSound;
var explodeSound2;
var explodeSound3;
var 

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.