Android MediaPlayer OnPreparedListener

I am working on a simple application and use MediaPlayer to play some background noise in 1 activity. I am reading on MediaPlayer and not sure if I need to implement OnPreparedListener to run the start () method. What are the advantages / disadvantages of each approach?

Approach 1:

mediaPlayer = MediaPlayer.create(context, R.raw.sound); mediaPlayer.setLooping(true); mediaPlayer.start(); 

Approach 2:

  mediaPlayer = MediaPlayer.create(context, R.raw.sound); mediaPlayer.setLooping(true); mediaPlayer.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); } }); 
+7
android media
source share
2 answers

According to the docs, calling start() effective when you play locally available resources for which MediaPlayer does not require fetching data and processing it for playback. For example, playing audio resources from the source folder.

If you are trying to play a resource from a remote source, it is best to use it for OnPreparedListener() , as it may include retrieving and decoding media.

So, if you know for sure that your resource is locally available and has a small length, go to Approach 1 . Otherwise, Approach 2 is suitable.

Ideally, I prefer that.

 MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setDataSource(getApplicationContext(), myUri); mediaPlayer.setOnPreparedListener(new OnPreparedListener(){ @Override public void onPrepared(MediaPlayer mp) { mp.start(); } }); mediaPlayer.prepareAsync(); 

It has always been difficult for me to work with MediaPlayer . Therefore, I would advise you to start with the developer documentation . Go through it, understand the state diagram. I am sure that this will help you resolve many issues that you still have to face.

+13
source share

let's say that you play a video from the internet , and if you press the start of the player, it will crash because it may not be ready for the game due to some internet problem or something else. and if you use a preparedlistener , then it will not start the player until it is ready for playback. therefore, it is good to have an onpreparedlistener so that your activity does not fail or does not work.

0
source share

All Articles