Ch018 - Polish: Add Soundtrack Music

Ch018 - Polish: Add Soundtrack Music

Polish: Add Soundtrack Music

Adding background music to a game gives a lot of advantages. You can really set the tone of the kind of game you are creating.

Check the Code: what we need to know and do

The code for a minimal example of the Add a Music Soundtrack game polish element is shown here -
https://jamm-labs.github.io/ggcp/add-polish-soundtrack-archive/game.js

We can add a sound track to our game to act as a bit of background music or a sound effect while we play. For this demo let’s just add a noise that lasts for 2 seconds.

To do this we load a new sound to our project in preload with the following linke

  game.load.audio('backgroundnoise' , 'https://cdn.glitch.com/04f51d70-ab26-4960-8e87-12f2aa251cff%2Fbackground_noise.wav');

Then we can create a variable with that loaded noise with the following lines in our playState.create function

  var backgroundNoise = game.sound.add("backgroundnoise", 1, true);
  backgroundNoise.play();

The game.sound.add() function here has three parameters.

  1. The “backgroundnoise” here is the name of the sound as defined in preload
  2. The number 1 here is the volume of the sound. To make it lower you could halve the volume by changing it to 0.5 for example.
  3. the true value here says if we should loop this sound or not, false plays it once, true means it does play over and over again.

The default for the volume parameter is level 1 (100%), and the default value for loop is false, so it only plays once.

So in this case we have to include a value for the volume parameter if we want to set the third loop parameter to true or the function will get confused.

You may notice a glitch! Adding a background track in this way may result in multiple versions of your tune being played if you get killed. To avoid this add the following line before the two lines adding and playing your audio in playState.create.

  game.sound.stopAll();

This will stop the multi versions of your song playing at the same time.