Featured Posts

Play music using MusicPlayer class in Android SDK

Author: Ngoc Khanh Tran – s3312498

I – Introduction:

Music is one of the most important aspects of live. In real live, it helps people relax, release their stress and merge themselves into the songs. In Android environment, music can event do better: It can be used as decoy for game applications, used as SFX when pressing buttons or event used as background theme for the applications. Therefore, this tutorial will talk about how to implements music in an Android Application.

II – Advantages and disadvantages:

Adding music will eat the memory of the device. If the application has both background and SFX music, the eaten memory will be big.

However, adding music brings the real feeling for the application and separates it from the static application. In some type of application, playing music is vital (Music player application, Alarm application…).

III – Requirement:

In Android SDK, there is a class name MediaPlayer in android.media.MediaPlayer that can be used to play music. It supports many types of music, including MP3, WAV, FLAC, AAC and MIDI.  For the other types, there are many proper libraries on the Internet.

This tutorial will demonstrate how to use the MediaPlayer class in a simple Music Player application. From this part the readers are assumed to have basic knowledge about Android GUI programming.

IV – Implement:

The first step is to create the GUI for the application. Since this is a simple Music player, there will be only two buttons in it: One is Play button (id btnPlay) and the other is Stop button (id btnStop). The GUI is simply present as below:

To play the music, first we need to initialize the MediaPlayer object inside the Activity:

       MediaPlayer mp = MediaPlayer.create(this.getApplicationContext(), R.raw.music_name);
       //This command create new MediaPlayer for music control
       //R.raw.music_name: The name of the song

After initialize, check if button Play or Stop is press and act as pre-defined:

public void onClick(View view) {

//check which button is pressed
switch (view.getId()) {

//Play button is pressed
       case R.id.btnPlay:
              if (mp.isPlaying())  {
                     mp.start();                    //play music
              } else {
                     mp.pause();                    //pause music
              }
              break;

//Stop button is pressed
       case R.id.btnStop:
              mp.stop();                         //stop music
              break;
       }
}

It is not hard to implement this code. One last thing to remember is to release all the Media Connection by using

       mp.release();

when you have  done with the music play. This will prevent Android application from being memory leaks.

Standard

Leave a comment