Android: MediaPlayer onPrepared is not being called

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 21:46:52

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!