FLOSS Manuals

 English |  Español |  Français |  Italiano |  Português |  Русский |  Shqip

Learn JavaScript with Phaser

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

Adding a soundtrack has some similar elements to adding a sound effect which we did in another chapter;

The code for a minimal example of the Add a Music Soundtrack game polish element is shown here -  https://add-polish-soundtrack.glitch.me/
 

Going over the code:

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

    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.

There has been error in communication with Booktype server. Not sure right now where is the problem.

You should refresh this page.