Playing music

Description

In this example we're going to find out how to load and play a music file.

AGK supports the MP3 format for music. This example will load and play a file named "music.mp3".

Process

The process involved is as follows:

Loading music

As with other resources music use ID numbers. These ID numbers are specifically for music files, so it's possible to have music loaded 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 order to load a music file we simply need to call the function LoadMusic and pass in a string that refers to MP3 Wave file, and save the returned ID number:

music = LoadMusic ( "music.mp3" )

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

For the sake of comparison here's the alternative approach. In this example instead of being assigned an ID number we specify it with the first parameter:

LoadMusic ( 1, "music.mp3" )

Playing music

Once music has been loaded it can be played with the PlayMusic command. Several variants of this command exist:

PlayMusic ( id )
playMusic ( id, loop )

The parameters for this command are as follows:

The ID number refers to the ID of the music you want to play. The loop parameter controls whether the music will be looped. When this value is set to 0 the music track will play through once and then stop. When this value is set to 1 the playback will continually loop.

To play and loop our previously loaded music this line is called:

PlayMusic ( 1, 1 )

Main loop

Our main loop doesn't need to take any action other than updating the screen with a call to Sync:

do
    Sync ( )
loop

Full code listing

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

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

LoadMusic ( 1, "music.mp3" ) PlayMusic ( 1, 1 )
do Sync ( ) loop

Conclusion

Loading and playing music is a process that can be handled with a minimal amount of code. Other functionality includes the ability to pause, resume, stop and delete music. It's also possible to set the volume of music using the command SetMusicSystemVolume. For more details on these commands please view the reference guide.