O'Reilly logo

Building HTML5 Games with ImpactJS by Jesse Freeman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding Music

Our game is a little boring without some background music. Luckily, Impact supports looping background music right out of the box. All we need to do is tell the music class what files to load and set the volume then call play(). Let’s go back into our main.js class and add the following at the beginning of the init() method:

ig.music.add( 'media/sounds/theme.*' );
ig.music.volume = 0.5;
ig.music.play();

Unlike playing sound effects, we will talk directly to the music class. We can add tracks to the music class, which will help us switch between different background music as we move through our game. Since we are only setting up one track, it will automatically get selected when you call play(). You can add more tracks via the add() method and select a track by calling ig.music.track() and passing in the ID of the track you want to play.

That is all there is to playing background music in your game. Before we move on, we should talk a little bit about browser compatibility and set expectations for when sounds will work and when it’s best not to play them.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required