Android App development - How to add and play music and audio files?

Android App development - How to add and play music and audio files?

Posted in android


Writing code to play music and audio files from an Android App is pretty straight forward thanks to the MediaPlayer class on the Android Platform. As with all development principles, there are things you should and shouldn't do.

As developers we're all used to embedding resources into our applications to keep things all together. Developing Android apps is no different, we can add as many resources as we like and reference them via the R class. One of the easiest ways to package up your audio files that you want to include with an Android app is to embed them as RAW resources. The Eclipse plugin does all the embedding hard work for you as long as you include your audio file in the res/raw folder of the project.

Step by Step



Follow these steps to include your audio file as a RAW embedded resource and play the file from within an Android App:

1. Put the sound/audio file (mp3, midi, aac or other supported format) in the res/raw folder of your project. The Eclipse plugin (or appt) will find that file and make it into a resource that the code can reference and use. This is done via the R class.

2. Next, we create an instance of the MediaPlayer class which we use to play audio files in Android apps. See below:

MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
mp.start();

As you can see, it's that simple. However, remember that the MediaPlayer class consumes memory and needs to be reset and prepared before you can play the audio again.

To reset and prepare the MediaPlayer just call:

mp.reset();
mp.prepare();

If you've finished using your MediaPlayer object then you should call the release method which pushes the object into the End state and disposes of it nicely. From here, the media player object we created is no longer usable, but is not consuming resources.

Further Reading



There are many other methods that you can call on the MediaPlayer class including; pause, seekTo, isLooping, setVolume. For a full list of methods visit the SDK section of the Android developer site:

MediaPlayer Class

For a full list of supported audio formats that you can use via the MediaPlayer class on Android visit:

Android MediaPlayer supported audio formats

For some free background music and intro tracks for use in your Android development visit our free music section:

Free music and audio for Android App Development