Skip to content

Getting Started: Sound and Audio

September 22, 2011

Let’s face it: sound is a big deal in games.  If you’ve ever played any video games, you know what I mean; some games are made by their music and sound effects; others are broken by them.  Now, you may want to think twice before making audio essential for your game- in the smartphone environment, many users will be muting their music.  Nevertheless, it is a big deal that can really make (or break) a great game.  So, the question is- how do you include music and sound effects in your games?

Enabling Music and Sound

Okay, so the first thing you need to do is tell the engine that it needs to look for sound.  In your onLoadEngine() code, include the bolded section of the following code:

return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera).setNeedsSound(true));
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera).setNeedsMusic(true));

And that’s all there is to enabling music.  With this, you’re ready to import your music and let it play!

Importing Music and Sound

The next thing to do for working with Music and Sound is to import it into the onLoadResources() section.  If you are looking to use a sound, try this code:

SoundFactory.setAssetBasePath(“mfx/”);

try {
	this.mySound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "mySoundFile.ogg");
} catch (final IOException e) {
	Debug.e(e);
}

For music, use this code:

MusicFactory.setAssetBasePath("mfx/");
try {
	this.myMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "myMusic.ogg");
	this.myMusic.setLooping(true);
} catch (final IOException e) {
	Debug.e(e);
}

In these examples, we have the audio placed in the folder mfx/ in order to make sure the project is organized- the first line of both examples is telling AndEngine to look in that directory.  Next, we have the code try… catch- this is an essential part of code (required by AndEngine) that makes sure the audio is there- but doesn’t cause your app to fall apart if it’s not.

Next, within the try, you define a variable- in this instance, Sound mySound and Music myMusic.  When given the music manager, context, and sound/music file, it puts it into a format that AndEngine can work with.  You’ll see one last difference between the music and sound file- that the music is given the command setLooping(true).  This is the first glimpse of one of the benefits AndEngine brings in its ability to deal with music and sound.

NOTE: there are a number of things that can cause music or sound not to play in a game.  One is a lack of resources: if the Android runs out of resources, it will often take sound out- because of this, it is important to make sure you use a bitrate that will keep your sound file from being to large.  The free program Audacity is a good resource for editing the fiiles down with the maximum retention of quality.  However, the more common reason (in my experience) for files not to play is that they are given the play command before the song is loaded.  Therefore it is important to place your music in onLoadResources, and the command to play it in onLoadComplete or later so that the user isn’t greeted with silence.

Playing Music and Sound

Once you load the music and sound, playing them is simple!  For the sound, play it like this:

mySound.play();

However, there is much more that can be done than just playing!  Here are a few of the most useful commands:

myMusic.pause();  myMusic.resume();  myMusic.stop();

These ones are pretty straight-forward- they pause, resume, or stop the music from playing.

myMusic.isPlaying();

If the song our sound file is playing, it returns true; if not, false.  It can be useful with sound effects- if it’s playing, stop it before playing again, so that you don’t end up playing too many sound effects at once and crashing your app.

myMusic.seekTo(int millisecond);

This code jumps the sound file to the millisecond defined by the int.

myMusic.setVolume(int volume) or (int leftVolume,int rightVolume);

If given one variable between 0 and 1 (in percent), this code sets the volume of the music to that number.  If given two variables, it sets the left volume and right volume separately.

myMusic.wait(long millisecond);

This code pauses the audio, then waits for the specified number of milliseconds before resuming it.

myMusic.setOnCompletionListener(onCompletionListener);

This code sets a listener that runs a section of code when the music has finished playing.

Legal Issues Concerning Music

Fantastic!  you may be thinking to yourself.  I’m going to go use one of my favorite game soundtracks for my game, such as the theme from Sonic the Hedgehog or Katamari Damacy.  I have bad news for you: if you do that, you’re most likely on your way to a lawsuit.  One of the biggest issues for Android and iPhone games is avoiding breaking legal copyright.  In the future, I’m hoping to write an entire post on the issue; in the meantime, I need to warn you- do not use anything copyrighted.  Best-case scenario, your game gets pulled from the market.

Check the license of every song you use.  Make sure you know whether or not they are available for use.  And if you’re not sure, it’s probably best to find something else- some other music that isn’t copyrighted.  For some samples of free music, check out AndEngine user Whalabi’s guide here.

Advertisements
3 Comments
  1. yjw permalink

    Hi, do you have any good strategy for detecting the completion of loading of sound/music assets? I have a clip that’s approximately 10seconds in duration, and there’s an intermittent problem where my game shows but the music is not playing. I’m suspecting its the async loading nature of the SoundPool, but I’m not too sure there’s any way to get around this.

    • I had the same problem with one of my games early on- one thing I found to be helpful was to compress the sound file with the free program Audacity- it also helped to convert it to .ogg format. You could try the code mMusic.isPlaying() which will return false if it is not playing, though you may not want to make it a part of a loop, as it can result in an infinite loop if the device won’t play the sound. I’ve had pretty good luck when defining the music in onLoadResources() and not playing it until onLoadComplete, though- make sure you’re not trying to play it before it has time to load. I’ll edit that into the guide- thanks for reminding me of it.

  2. yjw permalink

    I loaded my sound in onLoadResources() and left it to the very last moment I thought was possible by overriding onResumeGame, but the problem remains even and intermittently the sound will not play, even when I explicitly check that the Sound instance is not null.

    I guess that is the best we can do at this stage, unless AndEngine gets upgraded to take advantage of the change in Android API 8 for SoundPool callback on complete loading of sound resources.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: