Background Music
No arcade action game is complete without some pumping background music to make you feel like you’re in space. In this task we will add sound background audio to our game so that the player feels more immersed in the setting.
Task Definition
In this task we’re simply going to add a music file to the game and set it playing as soon as the game starts.
- (Optional) If you want to add your own theme to the game, go online and find an MP3 file that you would like as your background music and save it to assets/music/
- Preload the audio like you did with the background image, except using this.load.audio(name, filePath);.
- Create an audio object in your game using this.music = this.sound.add(name);. Audio objects exist on your stage just like graphics - only they don’t draw anything.
- Use the audio object you just created to play your music using this.music.play();.
Tip: Check out the title-screen.js file to see how it works there.
Walkthrough
1. Add the Audio to your Project
As with many of the other tasks, the first step is to add the music files you want to play to your game. A good place for them is;
assets/music/...
You’re welcome to use the music files that come bundled with the template project or you can head online and grab your own audio files if you would prefer! You can use .ogg or .mp3 files for the background music (although .mp3 files don’t always work in FireFox, they’re fine for this project).
2. Preload the Audio
Just like when you preload images, you also need to preload the audio that your game will play. You can do so with the following method;
this.load.audio(name, filePath);3. Play the Audio
Playing audio is similar to adding sprites to the world - only music requires an extra step. First, you need to add an ‘Audio Object’ to the game world which gives you control over the sound effect you want to play. You can use the audio object to start or stop the audio as well as changing the volume. One of the bonus quests will see you changing the music volume of the music depending on how busy the action is at the moment!
The following code snippets will come in handy when playing music in the game.
this.music = this.sound.add('game-music');
this.music.play();Extensions
- Try setting the volume property on this.music to change the volume between 0 and 1.
- You probably want to set the music to loop using the loop (boolean) property.
- You might want to consider adding a few different music tracks to your game and play one at random when the game starts.
Task Solution
This snippet shows just the changes that need to be added to your code to complete this task;
preload()
{
// Existing code...
this.load.audio('game-music', 'assets/music/maingame.mp3');
}
create()
{
this.music = this.sound.add('game-music');
this.music.play();
this.music.volume = 0.5;
this.music.loop = true;
// Existing code...
}