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:

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?

  1. The first argument is known. That’s the audio file.
  2. 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.
  3. Next comes the volume. Volume scales from zero to one, with a default of 1.
  4. 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.