How Android mediaplayer plays audio

Time:2020-8-12

This paper mainly introduces how to play audio with mediaplayer. For basic knowledge of mediaplayer, such as status, you can refer to the basic introduction of Android mediaplayer.

For the convenience of expression, define the variable named mediaplayer.

How to use mediaplayer

Create mediaplayer

You can create a new mediaplayer directly or by using the Create method provided by mediaplayer.

mediaPlayer = new MediaPlayer();

After creating successfully with the Create method, mediaplayer is in the prepared state. It can be started and played directly.


mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.fromFile(file));
mediaPlayer.start();

Set sound source – setdatasource

Set the sound source by calling setdatasource. Setdatasource has several overload methods. Let’s look at several common methods.

For example, set to use the resources in assets. Try catch may be required.


AssetFileDescriptor fd = null;
MediaPlayer mediaPlayer = new MediaPlayer();
fd = context.getApplicationContext().getAssets().openFd(name);
mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());

Local file, the absolute path of the file is required.


mediaPlayer.setDataSource(file.getAbsolutePath());

Or get the URI of the file to create the mediaplayer.


mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.fromFile(file));

Set the network audio, and also use the setdatasource method to set the URL.

mediaPlayer.setDataSource(“https://demo.com/sample.mp3”));

When playing network audio, if you use HTTP, you may report an error


java.io.IOException: Cleartext HTTP traffic to demo.com not permitted

You can simply set the manifest, set theusesCleartextTraffic=”true”


<application
 android:usesCleartextTraffic="true">

Prepare

Prepare audio resources synchronously and asynchronously.prepareAsync()It is asynchronous, and prepare is synchronous. Pay attention to thread scheduling and do not block UI threads.

Prepare audio asynchronously, often withMediaPlayer.OnPreparedListenerMonitor is used together. Other settings can also be made when preparing asynchronously.

mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
 @Override
 public void onPrepared(MediaPlayer mediaPlayer) {
 mediaPlayer.start (); // play when you are ready
 }
});

Loop – looping

Set loop playback setlooping.

mediaPlayer.setLooping(true);

After playing, the oncompletionlistener is not called back, but the current audio is played from the beginning.

Play – start

Play the audio and call the start method.

mediaPlayer.start();

When in the prepared, pause and playbackcomplete States, you can call the start method to enter the started state.

Pause

Pause the playback and use the pause method. Before pausing, judge whether the media player is playing.


if (mediaPlayer.isPlaying()) {
 mediaPlayer.pause();
}

 

If the pause is successful, it is in the suspended state.

Stop stop

Looking back at the diagram of mediaplayer state switching, we can know that in the three states of playing, pause and play completion, you can call the stop method to enter the stopped state.

mediaPlayer.stop();

Schedule adjustment seekto

Adjust the playback progress. We usually use music player software will have this function.
The seekto method takes a millisecond parameter.


int targetMS = (int) (percent * mediaPlayer.getDuration());
mediaPlayer.seekTo(targetMS);

 

Seekto does not change the state of mediaplayer.


int targetMS = (int) (percent * mediaPlayer.getDuration());
mediaPlayer.seekTo(targetMS);

The media player after reset enters idle state. Need to reset the sound source and prepare.

Release

When the media player is no longer used, it should be released as soon as possible to release related resources.

After release is called, mediaplayer enters the end state. At this point, the media player can no longer be used.

Common monitors

Buffering listener onbufferingupdatelistener

For example, when we load network audio, we often use this monitor to monitor the buffer progress. Showing buffering progress can also improve the user experience.

mMediaPlayer.prepareAsync();
mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
 @Override
 public void onBufferingUpdate(MediaPlayer mp, int percent) {
 //Percent is the buffer percentage
 }
});

Error listener onerrorlistener

mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
 @Override
 public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
 Return true; // return TRUE indicates that the error is handled here, and oncompletion will not be called back
 }
});

Note the return value of onerror. You can choose to handle the error yourself.


 * @return True if the method handled the error, false if it didn't.
 * Returning false, or not having an OnErrorListener at all, will
 * cause the OnCompletionListener to be called.
 */
boolean onError(MediaPlayer mp, int what, int extra);

On completion listener

mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
 @Override
 public void onCompletion(MediaPlayer mediaPlayer) {
 //It's over
 }
});

Examples of use

Play the audio from assets

Play the audio file in assets and use the assetfiledescriptor class. Remember to close assetfiledescriptor after use.


private void playAssetsAudio(final String name, Context context) {
 Log.d(TAG, "playAssetWordSound: try to play assets sound file. -> " + name);
 AssetFileDescriptor fd = null;
 try {
 MediaPlayer mediaPlayer;
 Log.v(TAG, "Looking in assets.");
 fd = context.getApplicationContext().getAssets().openFd(name);
 mediaPlayer = new MediaPlayer();
 mediaPlayer.reset();
 mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
 mediaPlayer.prepareAsync();
 mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
  @Override
  public void onPrepared(MediaPlayer mediaPlayer) {
  Log.d(TAG, "onPrepared: " + name);
  mediaPlayer.start();
  }
 });
 mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  @Override
  public void onCompletion(MediaPlayer mp) {
  mp.release();
  Log.d(TAG, "onCompletion: " + name);
  }
 });
 mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
  @Override
  public boolean onError(MediaPlayer mp, int i, int i1) {
  mp.release();
  return true;
  }
 });
 } catch (Exception e) {
 try {
  if (fd != null) {
  fd.close();
  }
 } catch (Exception e1) {
  Log.e(TAG, "Exception close fd: ", e1);
 }
 } finally {
 if (fd != null) {
  try {
  fd.close();
  } catch (IOException e) {
  Log.e(TAG, "Finally, close fd ", e);
  }
 }
 }
}

Play local audio files

Try playing the audio file. Play only once.


private void playAudioFile(final File file) {
 Log.d(TAG, "playAudioFile: " + file.getAbsolutePath());
 MediaPlayer mediaPlayer;
 try {
 mediaPlayer = new MediaPlayer();
 mediaPlayer.setLooping(false);
 mediaPlayer.setDataSource(file.getAbsolutePath());
 mediaPlayer.prepare();
 mediaPlayer.start();
 mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  @Override
  public void onCompletion(MediaPlayer mp) {
  mp.release();
  }
 });
 mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
  @Override
  public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
  Log.d(TAG, "Play local sound onError: " + i + ", " + i1);
  return true;
  }
 });
 } catch (Exception e) {
 Log.e(TAG, "playAudioFile: ", e);
 }
}

Play online audio

Set URL to play online audio


private void playOnlineSound(String soundUrlDict) {
 try {
 MediaPlayer mediaPlayer = new MediaPlayer();
 mediaPlayer.setDataSource(soundUrlDict);
 mediaPlayer.prepareAsync();
 mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
  @Override
  public void onPrepared(MediaPlayer mediaPlayer) {
  mediaPlayer.start();
  }
 });
 mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  @Override
  public void onCompletion(MediaPlayer mp) {
  if (mp != null) {
   mp.release();
  }
  Log.d(TAG, "onCompletion: play sound.");
  }
 });
 mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
  @Override
  public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
  Log.d(TAG, "Play online sound onError: " + i + ", " + i1);
  return false;
  }
 });
 } catch (IOException e1) {
 Log.e(TAG, "url: ", e1);
 }
}

The code can refer to the example project: https://github.com/RustFisher/android-MediaPlayer

summary

The above is how Android media player plays audio. I hope it will be helpful to you. If you have any questions, please leave me a message, and the editor will reply to you in time. Thank you very much for your support to the developeppaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]