SoFunction
Updated on 2025-03-11

Detailed explanation of the basic usage methods of MediaPlayer in Android development

This article describes the basic usage method of Android MediaPlayer. Share it for your reference, as follows:

The easiest example of using MediaPlayer to play audio or video:

Java code part:

public class MediaPlayerStudy extends Activity {
  private Button bplay,bpause,bstop;
  private MediaPlayer mp = new MediaPlayer();
  @Override
  public void onCreate(BundlesavedInstanceState) {
    (savedInstanceState);
    setContentView();
    bplay =(Button)findViewById();
    bpause =(Button)findViewById();
    bstop =(Button)findViewById();
    (new OnClickListener(){
      @Override
      public void onClick(View v) {
         try {
           ("/sdcard/test.mp3");
           ();
           ();
         } catch (IllegalArgumentException e){
           ();
         } catch (IllegalStateException e){
           ();
         } catch (IOException e) {
           ();
         }
         (new OnCompletionListener(){
           @Override
           public void onCompletion(MediaPlayer mp){
             ();
           }
         });
      }
    });
    (new OnClickListener(){
      @Override
      public void onClick(View v) {
         if(mp != null){
           ();
         }
      }
    });
    (new OnClickListener(){
    @Override
    public void onClick(View v) {
       if(mp != null){
        ();
       }
    }
    });
  }
  @Override
  protected void onDestroy() {
    if(mp != null)
      ();
    ();
  }
}

Layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Andro
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="@string/hello" />
    <Button android:text="play" android:
      android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
    <Button android:text="pause" android:
      android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
    <Button android:text="stop" android:
      android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
  </LinearLayout>

Program Description:

This example only describes the basic usage steps and methods of MediaPlayer. MediaPlayer also has a variety of usage methods and methods, and is not limited to the one introduced in the example. Specifically:

1) How to get MediaPlayer instance:

You can use the direct new method:

MediaPlayer mp = new MediaPlayer();

You can also use create, such as:

MediaPlayer mp = (this, );
//No need to call setDataSource at this time

2) How to set the file to play:

The files to be played by MediaPlayer mainly include 3 sources:

a. Users' resource resources in advance in the application

For example:

(this,);

b. Media files stored in SD card or other file paths

For example:

("/sdcard/test.mp3");

c. Media files on the network

For example:

("/music/confucius.mp3");

There are four methods for setDataSource of MediaPlayer:

setDataSource(String path)
setDataSource(FileDescriptor fd)
setDataSource(Context context, Uri uri)
setDataSource(FileDescriptor fd, long offset, long length)

3) Main control methods on the player:

Android controls the playback of media files by controlling the state of the player, where:

prepare()andprepareAsync()There are two ways to set the player to enter the prepare state by synchronous and asynchronous. It should be noted that if the MediaPlayer instance is created by the create method, then prepare() is no longer needed to be called before starting the playback for the first time, because the create method has been called.
start()It is the way to really start file playback.
pause()andstop()It is relatively simple, and it plays a role in pausing and stopping playback.
seekTo()It is a positioning method, which allows the player to start playing from the specified position. It should be noted that this method is an asynchronous method, which means that when the method returns, it does not mean that the positioning is completed, especially for the played network file. () will be triggered when the positioning is completed. If necessary, you can call setOnSeekCompleteListener (OnSeekCompleteListener) to set the listener to handle it.
release()The player can be freed, and once it is determined that the player is no longer used, it should be called as early as possible to release the resource.
reset()The player can be restored from the Error state and will return to the Idle state.

4) Set the listener of the player:

MediaPlayer provides some methods to set up different listeners to better monitor the working state of the player, in order to deal with various situations in a timely manner.

like:

setOnCompletionListener( listener)
setOnErrorListener( listener)etc. When setting up the player, you need to consider the possible situations of the player to set up the listening and processing logic to maintain the robustness of the player.

For more information about Android related content, please check out the topic of this site:Android multimedia operation skills summary (audio, video, recording, etc.)》、《Android development introduction and advanced tutorial》、《Android View View Tips Summary》、《Android programming activity operation skills summary》、《Android file operation skills summary》、《Android resource operation skills summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.