Android MediaPlayer OnPreparedListener

走远了吗. 提交于 2019-11-28 11:13:52

As per the docs, calling start() is effective when you are playing locally available resources for which the MediaPlayer does not require to fetch the data and process it for playing. For example playing audio resources from raw folder.

If you are trying to play a resource from remote source, its a better practice to go for OnPreparedListener() because it might involve fetching and decoding media data.

So, if you know for sure, that your resource is locally available and is of short length, go for Approach 1. Otherwise Approach 2 would be suitable.

Ideally, I prefer this.

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();

The MediaPlayer has always been tricky for me to work with. So, I would recommend you to start with the developer docs. Go through it, understand the state diagram. I am sure it will help you in solving lot of questions which you are yet to come across.

let say you are playing video from internet and if you direct start the player it would crash because it may be not ready to play because of some internet problem or something else. and if you use preparedlistener then it will not start the player until it is ready to play. therefore it is good to have onpreparedlistener so your activity does not crash or misbehaves.

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