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
play(). Let’s go back into our
main.js class and add the following at
the beginning of the
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
play(). You can add more tracks
add() method and select a track
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.