The idea is to store all sounds in an array and then play the right song according to what’s going on in the game. We are going a property in playGame object called soundArray. It’s defined as an empty array and will be visible only inside playGame object.
We declare it this way:
1 2 3 4 5 6 7 8 9 10 |
playGame.prototype = { soundArray: [], preload: function() { game.load.spritesheet("tiles", "tiles.png", tileSize, tileSize); game.load.audio("select", ["select.mp3", "select.ogg"]); game.load.audio("right", ["right.mp3", "right.ogg"]); game.load.audio("wrong", ["wrong.mp3", "wrong.ogg"]); }, ... } |
In the same playGame object, inside create method once we called placeTiles and we add the audio if the player selected the option to play with sound, that is if playSound is set to true.
A small change to create method:
1 2 3 4 5 6 7 8 |
create: function() { this.placeTiles(); if (playSound) { this.soundArray[0] = game.add.audio("select", 1); this.soundArray[1] = game.add.audio("right", 1); this.soundArray[2] = game.add.audio("wrong", 1); } } |
To insert elements into an array we always used push method but you can also declare items one by one assigning a value for a given index, like I did in these latest lines of code.
add.audio(key, volume) adds a new audio file to the sound manager. key is the name we gave to the sound, while volume is playing volume. It ranges from 0 to 1 where 1 means maximum volume.
Now that the sounds are preloaded and ready to be played, it’s time to insert our first sound into showTile method. This will be played when a tile is shown:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
showTile: function(target) { if(selectedArray.length < 2 && selectedArray.indexOf(target) == -1) { if(playSound) { this.soundArray[0].play(); } target.frame = target.value; selectedArray.push(target); if(selectedArray.length == 2) { game.time.events.add( Phaser.Timer.SECOND, this.checkTiles, this ); } } } |
Obviously before playing any sound effect we must check for playSound to be true.
play() method plays a sound.
Play the game, pick tiles and you should hear the sound effect. In the same way it’s easy to add sounds to checkTiles method, one to be played when the player made a successful match and one to be played when there wasn’t any match.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
checkTiles: function() { if(selectedArray[0].value == selectedArray[1].value) { if(playSound) { this.soundArray[1].play(); } selectedArray[0].destroy(); selectedArray[1].destroy(); } else { if(playSound) { this.soundArray[2].play(); } selectedArray[0].frame = 10; selectedArray[1].frame = 10; } selectedArray.length = 0; } |
Sounds gave the game a deeper experience, but there’s still a missing key feature, which is the one we all play for: the score.
Download Source
File: playing-sounds.zip