Sounds and music within a game are very important. Using the right style of music and sound effects can alter how the player perceives the game.
Sounds can be used for
Damage.
Clicking menu items.
Providing audio feedback to the play.
Setting the scene with appropriate background music.
Alongside graphical effects.
Telling the player something has been done correctly.
Sound Effects
Go ahead and load in the sound snd_bell, as shown in Figure 14-1.
Create an object, obj_test and put in the following code in a Step Event:
/// @description Play sound on S
if keyboard_check_pressed(ord(“S”))
{
audio_play_sound(snd_bell,1,false);
}
This will play the sound snd_bell each time S is pressed. The false tells the game not to loop the sound and only play it once through. Setting to true would loop the sound.
Place an instance of this object into the room and test. You’ll notice that the bell will play and overlap each time you press S – which may be an undesired effect depending on how you want your game design. You have a couple of options to prevent this from happening.
Method one is to check if a sound is playing already, and if it is, don’t play the sound again.
Which would look like this:
/// @description Play sound on S
if keyboard_check_pressed(ord("S"))
{
if !audio_is_playing(snd_bell) audio_play_sound(snd_bell,1,false);
}
A second option is to stop the playing sound and play again from the beginning, which would look like this:
/// @description Play sound on S
if keyboard_check_pressed(ord("S"))
{
if audio_is_playing(snd_bell) audio_stop_sound(snd_bell);
audio_play_sound(snd_bell,1,false);
}
Music
Add a new sound, snd_music_1 and load music_box from the resources.
Put the following code in to a Create Event of object obj_test:
/// @description Play music on loop
audio_play_sound(snd_music_1,1,true);
plays a music track on a continuous loop.
If you test now, you will hear the music playing on loop.
You can assign a sound to a variable, making it easier to refer to so you can perform actions on the sound, for example, by changing the Create Event code to:
You can get the length of a track in seconds with:
track_length=audio_sound_length(snd_bg_music);
Summary
You can now add in sounds and music and perform basic functions such as playing, pausing, resuming, and starting. You can check whether a sound is currently playing or not.