Website Links

Wednesday 25 June 2014

Adding Sound Effects with AndEngine

Recently, we've been hard at work on Alien Outlaw (our fastest growing game)! And we thought it was about time we brought it to another level by adding not only levels but sound too. But before you can add sound effects, you need sound effects... We used Bfxr to generate my sound effects. I then converted them to OGG using media.io. You don't need to use OGG but if you're interested in why it's a good option you can read about the differences between audio formats.

We're going to assume a basic knowledge of setting up an AndEngine activity. At some point we'll develop a full tutorial from start to finish but for now this is the best we can do. Also keep in mind that any ellipsis (...) mean that we omitted the details for brevity. First you will need to set in your onCreateEngineOptions that you will require sound using the following code:

EngineOptions options = new EngineOptions(...); options.getAudioOptions().setNeedsSound(true);

Next we need to specify the code for loading the sound, this should be placed in onCreateResources method as follows:

SoundFactory.setAssetBasePath("mfx/");
try {
this._explosionSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "explosion.ogg");

} catch (final IOException e) {
Debug.e(e);

}


The first line specifies that out sound files are located in the "mfx" directory within the assets directory. Then within the try-catch statement we try to set our private field of type Sound (_explosionSound). If the file exists and is of the format expected then the Debug statement should never be executed.

Finally, wherever you want to play a sound you've loaded, you call .play() on the sound object. If you have any questions, just ask!

No comments:

Post a Comment