Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

media - Android MediaPlayer OnPreparedListener

I am working on a simple app and using a MediaPlayer to play some background noise in 1 activity. I am reading up on MediaPlayer and am not sure whether or not to implement an OnPreparedListener to trigger the start() method. What are the pros / cons to 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();

        }
    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...