In the previous post, we added the scrolling starfield background. This made a big difference to the "feel" of the demo. And using the framework, this could be achieved with just a few lines code.
Sound effects can also make a big difference, and with Phaser, playing sound is also very easy.
Loading sound files
First you need to load in the sound files, in the preload function. There are lots of free sound available on the internet, but to be consistent with our previous examples, we will poach from the files created by the phaser team for their examples.
To handle sounds, Phaser provides a AudioSoundManager. To load the sound files, you use the this.load.audio method.
I have chosen to load just 2 sound files to include for now, by inserting the following lines in the preload function (I will actually be using only the firebullet sound in this example).
//load sound effects
this.load.audio('firebullet', "assets/audio/SoundEffects/lazer.wav");
this.load.audio('explode', "assets/audio/SoundEffects/explode1.wav");
There are many different files in the folder below, so you may like to experiment yourself.
You will find that there are sound files of different formats, including wav, mp3 and ogg. The Phaser docs notes that not all browser can play all audio formats. From what I understand, wav files is a safe bet.
mp3 and ogg formats can also be played by the majority of browsers, but there are some very old browsers that do not handle these formats. You will find in the phaser.io folder, some sound files available in both mp3, and ogg. There is an option in this.load.audio method to give it the file names of 2 audio files of different formats (eg mp3 and ogg), and the Phaser Manager will pick the one that can be played by the browser.
Creating the sound objects
Then you need to create a sound object (add the loaded sound files to Phaser's sound manager) by using the add method.
// create sound objects
bulletSound = this.sound.add('firebullet');
explodeSound = this.sound.add('explode');
Playing the sounds
Once the sound object has been created, the method to play the sound is...you guessed it. play(). By inserting the following line into the player class shoot method, the 'lazer.wav' sound is played every time a bullet is fired.
bulletSound.play()
And that's it for this example.
The entire CodePen Pen is available below for your perusal.
Comments