Home Tutorials Hints & Tips

Getting Started in Android Development

Part 24 - Playing Music with the Android MediaPlayer

In this tutorial we look at how to play music within an Android app. The music being on the form of an MP3 file or similar format. Details of supported media formats can be found here.

The Android MediaPlayer is best way to play music. It can support many compressed audio formats such as ACC and MP3. There are other methods available to developer to play sound. SoundPool is geared up toward short sound effects for games and the like and AudioTrack is optimised for uncompressed PCM data such as that contained in .WAV files or synthesized waveforms.

Any music file needs to be stored in a folder called raw under the resources folder. Create this if needed. An example is shown below:

Start by declaring a variable of type MediaPlayer

MediaPlayer mp;

Two buttons where assigned to the layout: start and stop. When the start button is pressed, it is simply a case of associating the instance of mp with the MP3 file in the raw directory and then starting the playback with the code below:

mp = MediaPlayer.create(getApplicationContext(), R.raw.sample_song);

When the stop button is pressed an ‘if’ statement is executed to ensure that MediaPlayer instance has been associated with the MP3 file and also if it is playing. If these conditions are true, it is simply a case of stopping the playback as below.

if (mp != null && mp.isPlaying()) {

At the simplest level that is all there is to it. In the next tutorial we will look at how to automatically stop the playback if the Activity is paused.

After this tutorial you MusicActivity.java file should look similar to the one below:

After this tutorial you activity_music.xml layout file should look similar to the one below:

After this tutorial you Android Manifest file should look similar to the one below:

After this tutorial you ListviewActivity.java file should look similar to the one below:

Download Download tutorial set 1

Privacy and Cookies Disclaimer Copyright
© 2015 - 2018 North Border Tech Training All rights reserved