Android Media Player Example: Mediaplayer Class
Android Media Player Example: Mediaplayer Class
We can play and control the audio files in android by the help of MediaPlayer class.
Here, we are going to see a simple example to play the audio file. In the next page, we will see
the example to control the audio playback like start, stop, pause etc.
MediaPlayer class
The android.media.MediaPlayer class is used to control the audio or video files.
There are many methods of MediaPlayer class. Some of them are as follows:
Method Description
sets the data source (file path or http url)
public void setDataSource(String path)
to use.
prepares the player for playback
public void prepare()
synchronously.
public void start() it starts or resumes the playback.
public void stop() it stops the playback.
public void pause() it pauses the playback.
public boolean isPlaying() checks if media player is playing.
public void seekTo(int millis) seeks to specified time in miliseconds.
sets the player for looping or non-
public void setLooping(boolean looping)
looping.
checks if the player is looping or non-
public boolean isLooping()
looping.
public void selectTrack(int index) it selects a track for the specified index.
public int getCurrentPosition() returns the current playback position.
public int getDuration() returns duration of the file.
public void setVolume(float leftVolume,float
sets the volume on this player.
rightVolume)
Activity class
Let's write the code of to play the audio file. Here, we are going to play maine.mp3 file located
inside the sdcard/Music directory.
File: MainActivity.java
1. package com.example.audiomediaplayer1;
2.
3. import android.media.MediaPlayer;
4. import android.net.Uri;
5. import android.os.Bundle;
6. import android.app.Activity;
7. import android.view.Menu;
8. import android.widget.MediaController;
9. import android.widget.VideoView;
10.
11. public class MainActivity extends Activity {
12.
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. MediaPlayer mp=new MediaPlayer();
19. try{
20. mp.setDataSource("/sdcard/Music/maine.mp3");//Write your location here
21. mp.prepare();
22. mp.start();
23.
24. }catch(Exception e){e.printStackTrace();}
25.
26. }
27.
28. @Override
29. public boolean onCreateOptionsMenu(Menu menu) {
30. // Inflate the menu; this adds items to the action bar if it is present.
31. getMenuInflater().inflate(R.menu.activity_main, menu);
32. return true;
33. }
34.
35. }
Let's see a simple example to start, stop and pause the audio play.
activity_main.xml
Drag three buttons from pallete to start, stop and pause the audio play. Now the xml file will look
like this:
File: MainActivity.java
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:id="@+id/textView1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentTop="true"
16. android:layout_marginTop="30dp"
17. android:text="Audio Controller" />
18.
19. <Button
20. android:id="@+id/button1"
21. style="?android:attr/buttonStyleSmall"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_alignLeft="@+id/textView1"
25. android:layout_below="@+id/textView1"
26. android:layout_marginTop="48dp"
27. android:text="start" />
28.
29. <Button
30. android:id="@+id/button2"
31. style="?android:attr/buttonStyleSmall"
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:layout_alignTop="@+id/button1"
35. android:layout_toRightOf="@+id/button1"
36. android:text="pause" />
37.
38. <Button
39. android:id="@+id/button3"
40. style="?android:attr/buttonStyleSmall"
41. android:layout_width="wrap_content"
42. android:layout_height="wrap_content"
43. android:layout_alignTop="@+id/button2"
44. android:layout_toRightOf="@+id/button2"
45. android:text="stop" />
46.
47. </RelativeLayout>
Activity class
Let's write the code to start, pause and stop the audio player.
File: MainActivity.java
1. package com.example.audioplay;
2.
3. import android.media.MediaPlayer;
4. import android.os.Bundle;
5. import android.os.Environment;
6. import android.app.Activity;
7. import android.view.Menu;
8. import android.view.View;
9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11.
12. public class MainActivity extends Activity {
13. Button start,pause,stop;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. start=(Button)findViewById(R.id.button1);
20. pause=(Button)findViewById(R.id.button2);
21. stop=(Button)findViewById(R.id.button3);
22. //creating media player
23. final MediaPlayer mp=new MediaPlayer();
24. try{
25. //you can change the path, here path is external directory(e.g. sdcard) /Music/m
aine.mp3
26. mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/m
aine.mp3");
27.
28. mp.prepare();
29. }catch(Exception e){e.printStackTrace();}
30.
31. start.setOnClickListener(new OnClickListener() {
32. @Override
33. public void onClick(View v) {
34. mp.start();
35. }
36. });
37. pause.setOnClickListener(new OnClickListener() {
38. @Override
39. public void onClick(View v) {
40. mp.pause();
41. }
42. });
43. stop.setOnClickListener(new OnClickListener() {
44. @Override
45. public void onClick(View v) {
46. mp.stop();
47. }
48. });
49. }
Output:
MediaController class
VideoView class
The android.widget.VideoView class provides methods to play and control the video player.
The commonly used methods of VideoView class are as follows:
Method Description
public void setMediaController(MediaController sets the media controller to the video
controller) view.
public void setVideoURI (Uri uri) sets the URI of the video file.
public void start() starts the video view.
public void stopPlayback() stops the playback.
public void pause() pauses the playback.
public void suspend() suspends the playback.
public void resume() resumes the playback.
seeks to specified time in
public void seekTo(int millis)
miliseconds.
activity_main.xml
Drag the VideoView from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <VideoView
8. android:id="@+id/videoView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_centerVertical="true" />
13.
14. </RelativeLayout>
Activity class
Let's write the code of to play the video file. Here, we are going to play 1.mp4 file located inside
the sdcard/media directory.
File: MainActivity.java
1. package com.example.video1;
2.
3. import android.net.Uri;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.view.Menu;
7. import android.widget.MediaController;
8. import android.widget.VideoView;
9.
10. public class MainActivity extends Activity {
11.
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. VideoView videoView =(VideoView)findViewById(R.id.videoView1);
18.
19. //Creating MediaController
20. MediaController mediaController= new MediaController(this);
21. mediaController.setAnchorView(videoView);
22.
23. //specify the location of media file
24. Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/media/
1.mp4");
25.
26. //Setting MediaController and URI, then starting the videoView
27. videoView.setMediaController(mediaController);
28. videoView.setVideoURI(uri);
29. videoView.requestFocus();
30. videoView.start();
31.
32. }
33.
34. @Override
35. public boolean onCreateOptionsMenu(Menu menu) {
36. // Inflate the menu; this adds items to the action bar if it is present.
37. getMenuInflater().inflate(R.menu.activity_main, menu);
38. return true;
39. }
40. } }
In this example, we are going to record the audio file and storing it in the external directory in
3gp format.
activity_main.xml
Drag 2 buttons from the pallete, one to start the recording and another stop the recording. Here,
we are registering the view with the listener in xml file using android:onClick.
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <Button
12. android:id="@+id/button1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="68dp"
18. android:layout_marginTop="50dp"
19. android:text="Start Recording"
20. android:onClick="startRecording"
21. />
22.
23. <Button
24. android:id="@+id/button2"
25. android:layout_width="wrap_content"
26. android:layout_height="wrap_content"
27. android:layout_alignLeft="@+id/button1"
28. android:layout_below="@+id/button1"
29. android:layout_marginTop="64dp"
30. android:text="Stop Recording"
31. android:onClick="stopRecording"
32. />
33.
34. </RelativeLayout>
Activity class
File: MainActivity.java
1. package com.javatpoint.mediarecorder;
2. import java.io.File;
3. import java.io.IOException;
4. import android.app.Activity;
5. import android.content.ContentResolver;
6. import android.content.ContentValues;
7. import android.content.Intent;
8. import android.media.MediaRecorder;
9. import android.net.Uri;
10. import android.os.Bundle;
11. import android.os.Environment;
12. import android.provider.MediaStore;
13. import android.util.Log;
14. import android.view.View;
15. import android.widget.Button;
16. import android.widget.Toast;
17.
18. public class MainActivity extends Activity {
19. MediaRecorder recorder;
20. File audiofile = null;
21. static final String TAG = "MediaRecording";
22. Button startButton,stopButton;
23.
24. @Override
25. public void onCreate(Bundle savedInstanceState) {
26. super.onCreate(savedInstanceState);
27. setContentView(R.layout.activity_main);
28. startButton = (Button) findViewById(R.id.button1);
29. stopButton = (Button) findViewById(R.id.button2);
30. }
31.
32. public void startRecording(View view) throws IOException {
33. startButton.setEnabled(false);
34. stopButton.setEnabled(true);
35. //Creating file
36. File dir = Environment.getExternalStorageDirectory();
37. try {
38. audiofile = File.createTempFile("sound", ".3gp", dir);
39. } catch (IOException e) {
40. Log.e(TAG, "external storage access error");
41. return;
42. }
43. //Creating MediaRecorder and specifying audio source, output format, encoder &
output format
44. recorder = new MediaRecorder();
45. recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
46. recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
47. recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
48. recorder.setOutputFile(audiofile.getAbsolutePath());
49. recorder.prepare();
50. recorder.start();
51. }
52.
53. public void stopRecording(View view) {
54. startButton.setEnabled(true);
55. stopButton.setEnabled(false);
56. //stopping recorder
57. recorder.stop();
58. recorder.release();
59. //after stopping the recorder, create the sound file and add it to media library.
60. addRecordingToMediaLibrary();
61. }
62.
63. protected void addRecordingToMediaLibrary() {
64. //creating content values of size 4
65. ContentValues values = new ContentValues(4);
66. long current = System.currentTimeMillis();
67. values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName());
68. values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
69. values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
70. values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
71.
72. //creating content resolver and storing it in the external content uri
73. ContentResolver contentResolver = getContentResolver();
74. Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
75. Uri newUri = contentResolver.insert(base, values);
76.
77. //sending broadcast message to scan the media file so that it can be available
78. sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, new
Uri));
79. Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();
80. }
81. }