Android Audio / Media Player with Examples

In android, by using MediaPlayer class we can easily fetch, decode and play both audio and video files with minimal setup.

 

The android media framework provides built-in support for playing a variety of common media types, such as audio or video. We have multiple ways to play audio or video but the most important component of media framework is MediaPlayer class.

Android MediaPlayer Class

In android, by using MediaPlayer class we can access audio or video files from application (raw) resources, standalone files in file system or from a data stream arriving over a network connection and play audio or video files with the multiple playback options such as play, pause, forward, backward, etc.

 

Following is the code snippet, to play an audio that is available in our application’s local raw resource (res/raw) directory.

 

MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.baitikochi_chuste);
mPlayer.start();

The second parameter in create() method is the name of the song that we want to play from our application resource directory (res/raw). In case if raw folder not exists in your application, create a new raw folder under res directory and add a properly encoded and formatted media files in it.

 

In case, if we want to play an audio from a URI that is locally available in the system, we need to write the code like as shown below.

 

Uri myUri = ....; // initialize Uri here
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(getApplicationContext(), myUri);
mPlayer.prepare();
mPlayer.start();

If we want to play an audio from a URL via HTTP streaming, we need to write the code like as shown below.

 

String url = "http://........"; // your URL here
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(url);
mPlayer.prepare(); // might take long! (for buffering, etc)
mPlayer.start();

If you observe above code snippets, we create an instance of MediaPlayer class and added required audio source, streaming type, audio file path, etc. to play an audio from our application.

 

Apart from above methods, MediaPlayer class provides a different type of methods to control audio and video files based on requirements.

 

MethodDescription
getCurrentPosition() It is used to get the current position of the song in milliseconds.
getDuration() It is used to get the total time duration of the song in milliseconds.
isPlaying() It returns true / false to indicate whether song playing or not.
pause() It is used to pause the song playing.
setAudioStreamType() it is used to specify the audio streaming type.
setDataSource() It is used to specify the path of audio / video file to play.
setVolume() It is used to adjust media player volume either up / down.
seekTo(position) It is used to move song to particular position in milliseconds.
getTrackInfo() It returns an array of track information.
start() It is used to start playing the audio/video.
stop() It is used to stop playing the audio/video.
reset() It is used to reset the MediaPlayer object.
release() It is used to releases the resources which are associated with MediaPlayer object.

Now we will see how to implement media playing application using MediaPlayer to play a song or audio with multiple playback options, such as play, pause, forward, backward in android application with examples.

Android Audio Player Example

Following is the example of implementing an audio player to play a song or audio with multiple playback options using MediaPlayer.

 

Create a new android application using android studio and give names as MediaPlayerExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

As discussed create a new raw folder in res directory and add one music file like as shown below to play it by using MediaPlayer class.

 

Android Audio Player Example - Add Raw Folder

 

Now open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:paddingLeft="10dp"
   
android:paddingRight="10dp">
    <
TextView
       
android:id="@+id/txtVw1"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Now Playing: "
       
android:layout_marginTop="30dp"
       
android:textAppearance="?android:attr/textAppearanceMedium" />
    <
TextView
       
android:id="@+id/txtSname"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_alignBaseline="@+id/txtVw1"
       
android:layout_toRightOf="@+id/txtVw1"
       
android:text="TextView" />
    <
ImageView
       
android:id="@+id/imgLogo"
       
android:layout_width="match_parent"
       
android:layout_height="450dp"
       
android:layout_below="@+id/txtVw1"
       
android:src="@drawable/tutlane" />
    <
ImageButton
       
android:id="@+id/btnBackward"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
        
android:layout_alignParentBottom="true"
       
android:layout_marginBottom="44dp"
       
android:layout_marginLeft="20dp"
       
android:src="@android:drawable/ic_media_rew" />
    <
ImageButton
       
android:id="@+id/btnPlay"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_alignTop="@+id/btnBackward"
       
android:layout_marginLeft="20dp"
       
android:layout_toRightOf="@+id/btnBackward"
       
android:src="@android:drawable/ic_media_play" />
    <
ImageButton
       
android:id="@+id/btnPause"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_alignTop="@+id/btnPlay"
       
android:layout_marginLeft="20dp"
       
android:layout_toRightOf="@+id/btnPlay"
       
android:src="@android:drawable/ic_media_pause" />
    <
ImageButton
       
android:id="@+id/btnForward"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_alignTop="@+id/btnPause"
       
android:layout_marginLeft="20dp"
       
android:layout_toRightOf="@+id/btnPause"
       
android:contentDescription="@+id/imageButton3"
       
android:src="@android:drawable/ic_media_ff" />
      <
TextView
       
android:id="@+id/txtStartTime"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_alignTop="@+id/sBar"
       
android:text="0 min, 0 sec" />
    <
SeekBar
       
android:id="@+id/sBar"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_above="@+id/btnBackward"
       
android:layout_toLeftOf="@+id/txtSongTime"
       
android:layout_toRightOf="@+id/txtStartTime" />
    <
TextView
       
android:id="@+id/txtSongTime"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_toRightOf="@+id/btnForward"
       
android:layout_alignTop="@+id/sBar"
       
android:text="0 min, 0 sec " />
</
RelativeLayout>

Now open your main activity file MainActivity.java from \java\com.tutlane.audioplayerexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.mediaplayerexample;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
   
private ImageButton forwardbtn, backwardbtn, pausebtn, playbtn;
   
private MediaPlayer mPlayer;
   
private TextView songName, startTime, songTime;
   
private SeekBar songPrgs;
   
private static int oTime =0, sTime =0, eTime =0, fTime = 5000, bTime = 5000;
   
private Handler hdlr = new Handler();
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
backwardbtn = (ImageButton)findViewById(R.id.btnBackward);
       
forwardbtn = (ImageButton)findViewById(R.id.btnForward);
       
playbtn = (ImageButton)findViewById(R.id.btnPlay);
       
pausebtn = (ImageButton)findViewById(R.id.btnPause);
       
songName = (TextView)findViewById(R.id.txtSname);
       
startTime = (TextView)findViewById(R.id.txtStartTime);
       
songTime = (TextView)findViewById(R.id.txtSongTime);
       
songName.setText("Baitikochi Chuste");
       
mPlayer = MediaPlayer.create(this, R.raw.baitikochi_chuste);
       
songPrgs = (SeekBar)findViewById(R.id.sBar);
       
songPrgs.setClickable(false);
       
pausebtn.setEnabled(false);

       
playbtn.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
                Toast.makeText(MainActivity.
this, "Playing Audio", Toast.LENGTH_SHORT).show();
               
mPlayer.start();
               
eTime = mPlayer.getDuration();
               
sTime = mPlayer.getCurrentPosition();
               
if(oTime == 0){
                   
songPrgs.setMax(eTime);
                   
oTime =1;
                }
               
songTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(eTime),
                        TimeUnit.
MILLISECONDS.toSeconds(eTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(eTime))) );
               
startTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(sTime),
                        TimeUnit.
MILLISECONDS.toSeconds(sTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(sTime))) );
               
songPrgs.setProgress(sTime);
               
hdlr.postDelayed(UpdateSongTime, 100);
               
pausebtn.setEnabled(true);
               
playbtn.setEnabled(false);
            }
        });
       
pausebtn.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
               
mPlayer.pause();
               
pausebtn.setEnabled(false);
               
playbtn.setEnabled(true);
                Toast.makeText(getApplicationContext(),
"Pausing Audio", Toast.LENGTH_SHORT).show();
            }
        });
       
forwardbtn.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
               
if((sTime + fTime) <= eTime)
                {
                   
sTime = sTime + fTime;
                   
mPlayer.seekTo(sTime);
                }
               
else
               
{
                    Toast.makeText(getApplicationContext(),
"Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show();
                }
               
if(!playbtn.isEnabled()){
                   
playbtn.setEnabled(true);
                }
            }
        });
       
backwardbtn.setOnClickListener(new View.OnClickListener() {
           
@Override
            
public void onClick(View v) {
               
if((sTime - bTime) > 0)
                {
                   
sTime = sTime - bTime;
                   
mPlayer.seekTo(sTime);
                }
               
else
               
{
                    Toast.makeText(getApplicationContext(),
"Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show();
                }
               
if(!playbtn.isEnabled()){
                   
playbtn.setEnabled(true);
                }
            }
        });
    }
   
private Runnable UpdateSongTime = new Runnable() {
       
@Override
       
public void run() {
           
sTime = mPlayer.getCurrentPosition();
           
startTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(sTime),
                    TimeUnit.
MILLISECONDS.toSeconds(sTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(sTime))) );
           
songPrgs.setProgress(sTime);
           
hdlr.postDelayed(this, 100);
        }
    };
}

If you observe above code we used MeidaPlayer object properties to play, pause song and changing the song position either forward or backward based on our requirements.

Output of Android Audio Player Example

When we run the above program in the android studio we will get the result as shown below.

 

Android Audio / Media Player with Example Result

 

If you observe above result, when we click on play button song will start play and it will show the song duration details. If we click on pause button, the song will stop playing and use forward and backward buttons to move song forward or backward based on your requirements.

 

This is how we can implement audio player app in android applications with multiple playback options based on our requirements.