The codeleap for this section may be accessed here. In this section, we will discuss Sounds and their application. Following this explanation, we will implement background music and sound effects.
01 A Word on Sound
02 Background Music
03 Sound Effects
The use of sounds in a game can really help enrich the player’s experience. They can be added as background music and sound effects like player reactions or general game sounds. Sound can really help get the player into the game, and might even have the player seeking the next in-game goal just to get the satisfaction of a rewarding sound effect.
So far, the most universal format for sounds that I’ve found is the OGG format. In my experience, when MP3s don’t work, they prevent the entire game from loading. WAV files also work across browsers, but if a WAV file is long enough, it ends up taking up too much space.
If you need to convert sound files across different formats, I highly recommend Audacity.
You can download it from here.
In order to use sounds, we must first add them to the preloader. Once they’ve been preloaded, we can reference them by name in the game’s assets.
i.e.) game.assets[‘SOME_FILE.ogg’].play() will play the preloaded sound file SOME_FILE.ogg
Background music can really contribute to a game’s mood. It can raise or alleviate tension, build up excitement, or even put the player in a state of panic. We will add a longer sound file to the preloader and use it as background music that loops as soon as it’s done playing.
Let’s implement a Sound in our example code. (Once again, you can access it from here.)
game.preload('icon0.png', 'bg.png', 'space3.png', 'diamond.png', 'unreal.ogg');
We will implement sound effects by preloading one, then calling the play() method from within a Gem sprite class when the player collides with a Gem sprite. In our example, the player can be moved around by clicking on a destination for the player sprite to move to.
game.preload('icon0.png', 'bg.png', 'space3.png', 'diamond.png', 'unreal.ogg', 'ping.wav');
onenterframefunction, under 09.3 Add Sound Effect add: