North Border Software




Home Tutorials Hints & Tips About

Android Apps and Training

Share on Facebook Share on Twitter

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);
mp.start();

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()) {
   mp.stop();
}

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


© 2015 North Border Software All rights reserved
Privacy and Cookies Terms of Use Disclaimer Copyright
North Border Software Logo