5.2.1 Music
A soundtrack can be played with the class Sound:
Sound soundtrack;
void InitPre()
{
5 EE_INIT();
}
bool Init()
{
10 soundtrack.create(=== drop your audio file here ===);
return true;
}
void Shut() {}
15
bool Update()
{
if(Kb.bp(KB_ESC)) return false;
20 if(Kb.bp(KB_SPACE))
{
if(soundtrack.playing())
{
soundtrack.pause();
25 } else
{
soundtrack.play();
}
}
30 return true;
}
There’s a few things to remember, though:
- Before you can use a sound, it must be loaded from disk. This is done with
the create() function. It needs at least one argument: the audio file. Like
with images, you can simply drag the file from your resources on to your
function. You will want to do this inside of the Init() function, because
you don’t want to load your file from disk at every update.
- play() will cause the sound to start playing.
- pause() will pause the sound. Who would have guessed, right? When you
use play after pause, the sound will continue right where it left off.
- Instead of pause() you can also use stop(). Now when you start playing
again, the sound will start from the beginning.
The create() function also has a few optional arguments. Here’s an example with all
of them:
soundtrack.create(=== audio file ===, true, 0.8, VOLUME_MUSIC);
But what do they mean, little grasshopper?
- The first argument is known. That’s the audio file.
- the second argument is the loop value. It can be true or false and is used
to indicate if you’d like the sound to ‘loop’. (Which mean it will start from
the top when it is finished.) The default value is false.
- Next comes the volume. Volume scales from zero to one, with a default of
1.
- The last argument is a ‘channel’. Esenthel has several channels for playing
audio. If you don’t use this argument, the sound will use the channel
‘VOLUME_FX’. It is generally a good idea to use several channels for
different types of sounds, because the volume of a channel can be changed.
It makes it easy to implement volume changes for music, fx or voices.
Exercise
Create an application which loads a soundtrack. Draw a green, an orange and a red
circle on the screen. The track should start playing when you click the green
circle, pause when you click the orange circle and stop when you click the red
one.
Exercise
Extra: Search the header file of the sound class for a method to retrieve
the current playing position within a sound file. Draw this position on the
screen.
Exercise
Extra: This will be a bit harder. Use the functions fadeInFromSilence() and
fadeOut() to apply a fade of 3 seconds instead of an immediate start and
stop.