Play a sound

Description

In this example we're going to find out how to load a sound file and play it when the user clicks / touches the screen.

We rely on an external piece of media for this example. It's a Wave file named "countdown.wav". AGK supports the Wave format for sound and the MP3 format for music.

Process

The process involved is as follows:

Load a sound

As with other resources sounds use ID numbers. These ID numbers are specifically for sounds, so it's possible to have a sound with an ID number of 1 and a sprite with an ID of 1. Just like with other resources it's possible to have an ID number assigned automatically or provide one yourself. Either approach works just as well. In this example we'll take the approach of automatically assigned ID numbers.

In order to load a sound we simply need to call the function LoadSound and pass in a string that refers to our Wave file, and save the returned ID number:

sound = LoadSound ( "countdown.wav" )

After calling this our file "countdown.wav" has been loaded into memory and ready to be used. We can later refer to it through the ID number we have saved in the variable sound.

For the sake of comparison here's the alternative approach:

LoadSound ( 1, "countdown.wav" )

In this example instead of being assigned an ID number we specify it with the first parameter. This may be more convenient in some cases as you don't have to store an ID number in a variable. The drawback is that as your project becomes larger it's likely to cause problems as you end up dealing with lots of numbers, whereas having it automatically assigned means you don't have to care about it.

Main loop

Within our main loop we will trigger the playing of our sound whenever the user touches / clicks the screen.

do
    if GetPointerPressed ( ) = 1
        PlaySound ( sound )
    endif

sync ( ) loop

As we're not interested in where the touch events take place, only that it has taken place, our input loop is fairly simple. It begins by initially checking for a touch event, followed by a call to PlaySound where we pass in the ID number of our sound.

Full code listing

Everything is now in place. Here's the final code for our program:

backdrop = CreateSprite ( LoadImage ( "background2.jpg" ) )
SetSpriteColorAlpha ( backdrop, 100 )
SetSpriteSize ( backdrop, 100, 100 )

sound = LoadSound ( "countdown.wav" )
do Print ( "Touch or click the screen" ) Print ( "to play a sound" )
if GetPointerPressed ( ) = 1 PlaySound ( sound ) endif
Sync ( ) loop

Conclusion

We're now all set to run our application and see the results on screen. Once the application has launched try touching the screen or clicking on it and listen for the sound being played.