Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: MediaPlayer onPrepared is not being called

As title says, the onPrepared() overridden method is not being called.

mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new OnPreparedListener(){
   @Override
   public void onPrepared(MediaPlayer mp){
      if (mp.equals(mediaPlayer)) isReady_mediaPlayer = true;

      Log.e("I", "Media player has been loaded to memory !");
   }
});

mediaPlayer = MediaPlayer.create(this, R.raw.my_sound_mp3);
like image 476
Zbarcea Christian Avatar asked Mar 23 '23 00:03

Zbarcea Christian


1 Answers

It's because you are creating a new MediaPlayer object. This one does not have any onPreparededListener set on it.

Here you create and assign a MediaPlayer object:

mediaPlayer = new MediaPlayer();

Next you set an onPreparedListener on it.

But then you create and assign a new one! This assignment overrides your previous lines.

mediaPlayer = MediaPlayer.create(this, R.raw.my_sound_mp3);

This one has no onPreparedListener set on it.

To fix, don't use the create method, use setDataSource instead

AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.my_sound_mp3);
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new OnPreparedListener(){
    @Override
    public void onPrepared(MediaPlayer mp){
       if (mp.equals(mediaPlayer)) isReady_mediaPlayer = true;
       Log.e("I", "Media player has been loaded to memory !");
    }
});
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepare();
like image 146
Ken Wolf Avatar answered Apr 01 '23 21:04

Ken Wolf