Android provides you different ways to control playback of audio/video files and streams. One of the ways to control the audio/video files is through MediaPlayer class.
MediaPlayer class can be used to access built-in mediaplayer services like playing audio,video, e.t.c. In order to use MediaPlayer, we have to call a static Method
create(), which returns an instance of MediaPlayer class. The following is the syntax for calling a static method:
Ex:
MediaPlayer player=MediaPlayer.create(this, R.raw.song);
After calling the create method, it is first required to call the
prepare()
method followed by the
start()
method.
Ex:
player.prepare();
player.start();
Apart from the above methods, there are other methods in this class such as:
• isPlaying(): This method just returns true/false stating whether the song is playing or not.
• getDuration(): This method returns the total time duration of song in milliseconds.
• getCurrentDuration(): This method returns the current position of song in milliseconds.
• seekTo(position): This method takes an integer, and moves the song to that particular second.
• stop(): This method stops the media player
• pause(): This method pauses the media player.
• setDataSource(FileDescriptor fd): This method sets the data source of audio/video file
The following example illustrates how to use the MediaPlayer in your application to play audio files, how to use seek bar to track the progress of the current record, and how to set the audio volume. Handler has been used to process Runnable objects associated with a thread's MessageQueue (audio tacking time).
Create MainActivity.java which implements
OnCompletionListener
in your project. You should override
onCompletion()
method and also create
res/raw folder to save any song.mp3.
Create MainActivity.java under src/package name.
MainActivity.java:
[java]
public class MainActivity extends Activity implements OnCompletionListener {
//variable declaration
Button play;
TextView time;
private int stateMediaPlayer;
private final int stateMP_Error = 0;
private final int stateMP_NotStarter = 1;
private final int stateMP_Playing = 2;
private final int stateMP_Pausing = 3;
SeekBar track,volume;
MediaPlayer player;
private double timeElapsed = 0;
Handler handler=new Handler();
String audio,title,desc;
AudioManager audioManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//set activity content to external layout
setContentView(R.layout.activity_main);
//find views by Id
play=(Button)findViewById(R.id.buttonPlay);
time=(TextView)findViewById(R.id.textViewTime);
track=(SeekBar)findViewById(R.id.seekBarTrack);
volume=(SeekBar)findViewById(R.id.seekBarVoloume);
audio=getIntent().getStringExtra("audio");
title=getIntent().getStringExtra("name");
desc=getIntent().getStringExtra("desc");
//initiate media player
initMediaplayer();
//on touch track(seek bar)
track.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent arg1) {
// TODO Auto-generated method stub
seekChange(v);
return false;
}
});
//on click play
play.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(stateMediaPlayer){
case stateMP_Error:
break;
case stateMP_NotStarter:
//playing audio for the first time
player.start();
timeElapsed = player.getCurrentPosition();
track.setProgress((int) timeElapsed);
handler.postDelayed(run, 100);
play.setBackgroundResource(R.drawable.pause);
stateMediaPlayer = stateMP_Playing;
break;
case stateMP_Playing:
//pause
player.pause();
play.setBackgroundResource(R.drawable.play);
stateMediaPlayer = stateMP_Pausing;
break;
case stateMP_Pausing:
//playing
player.start();
timeElapsed = player.getCurrentPosition();
track.setProgress((int) timeElapsed);
handler.postDelayed(run, 100);
play.setBackgroundResource(R.drawable.pause);
stateMediaPlayer = stateMP_Playing;
break;
}
}
});
//set volume
if(volume!=null){
audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
volume.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volume.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC)/2);
volume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
}
private void initMediaplayer()
{
try {
/*playing audio from server
player=new MediaPlayer();
player.setDataSource(url);*/
//palaying static audio which is under res/raw
player=MediaPlayer.create(this, R.raw.song);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(this);
player.prepare();
time.setText("00:00:00"+" / "+ String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours((long)player.getDuration()),
TimeUnit.MILLISECONDS.toMinutes((long)player.getDuration()) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours((long)player.getDuration())),
TimeUnit.MILLISECONDS.toSeconds((long)player.getDuration()) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)player.getDuration()))));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
track.setMax(player.getDuration());
//player.getDuration();
stateMediaPlayer = stateMP_NotStarter;
}
Runnable run=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
track.setProgress(player.getCurrentPosition());
timeElapsed = player.getCurrentPosition();
double millis = timeElapsed;
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours((long)millis),
TimeUnit.MILLISECONDS.toMinutes((long)millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours((long)millis)),
TimeUnit.MILLISECONDS.toSeconds((long)millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)millis)));
time.setText(""+hms+" / "+ String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours((long)player.getDuration()),
TimeUnit.MILLISECONDS.toMinutes((long)player.getDuration()) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours((long)player.getDuration())),
TimeUnit.MILLISECONDS.toSeconds((long)player.getDuration()) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)player.getDuration()))));
handler.postDelayed(run,100);
}
};
// This is event handler thumb moving event
private void seekChange(View v){
if(player.isPlaying()){
SeekBar sb = (SeekBar)v;
player.seekTo(sb.getProgress());
}
}
@Override
public void onCompletion(MediaPlayer mp) {
play.setBackgroundResource(R.drawable.play);
player.seekTo(0);
initMediaplayer();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
player.stop();
return super.onKeyDown(keyCode, event);
}
}
[/java]
Create activity_main.xml in res/layout folder.
activity_main.xml:
[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:orientation="vertical"
android:layout_gravity="center"
android:gravity="center"
android:background="#FFFFFF" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginBottom="65dp"
android:background="#FFFFFF" >
<TextView
android:id="@+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#009ACD"
android:layout_marginTop="10dp"
android:textSize="20sp"
android:layout_gravity="center"
android:text="MediaPlayer Example" />
<Button
android:id="@+id/buttonPlay"
android:layout_width="25dp"
android:layout_height="25dp"
android:background="@drawable/play"
android:layout_gravity="center"
android:layout_marginTop="10dp"/>
<SeekBar
android:id="@+id/seekBarTrack"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#555555"
android:textSize="15sp"
android:layout_marginLeft="30dp"
android:text="TrackTime" />
<TextView
android:id="@+id/textViewTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="30dp"
android:gravity="right"
android:textSize="15sp"
android:textColor="#555555"
android:text="00:00:00" />
</LinearLayout>
<SeekBar
android:id="@+id/seekBarVoloume"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="10dp" />
<TextView
android:id="@+id/textViewVolume"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#555555"
android:text="Volume" />
</LinearLayout>
</RelativeLayout>
[/xml]
AndroidManifest.xml:
[xml]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.spl.myproject"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.spl.myproject.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
[/xml]
Output: