Android - How to tell when MediaPlayer is bufferin

2019-01-31 18:04发布

I've got to be missing something obvious here, but I can't seem to find anything to allow me to determine when MediaPlayer is buffering audio. I'm streaming internet audio and I want to display a buffering indicator, but nothing I've tried allows me to know when MediaPlayer interrupts the audio to buffer, so I can't properly display a buffering indicator. Any clues?

5条回答
劫难
2楼-- · 2019-01-31 18:39

Ok, I feel a little vindicated now. I checked out the Pandora app and it doesn't display a buffering indicator. When music is interrupted for buffering, it just sits there as if nothing happened and the UI looks like it's still playing. So I've come to the conclusion that if you're using MediaPlayer, it's just not possible to determine if the track is temporarily paused for buffering.

However, I did notice that there are a couple MediaPlayer constants that could be of use: MEDIA_INFO_BUFFERING_START and MEDIA_INFO_BUFFERING_END. But they're only available in API level 9+, and the docs don't say anything about them. I'm assuming they can be used with an OnInfoListener.

I'm disappointed, but at least I can stop spinning my wheels now and move on to something else.

查看更多
Evening l夕情丶
3楼-- · 2019-01-31 18:40

Register an OnBufferingUpdate listener.

查看更多
倾城 Initia
4楼-- · 2019-01-31 18:41

Like below (API level ≥ 9):

mp.setOnInfoListener(new OnInfoListener() {

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                loadingDialog.setVisibility(View.VISIBLE);
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                loadingDialog.setVisibility(View.GONE);
                break;
        }
        return false;
    }
});

NOTE : There is a known bug in Android. When playing HLS stream it's just never calls OnInfoListener or OnBuffering. check this link OnInfoListener bug

查看更多
成全新的幸福
5楼-- · 2019-01-31 18:51

@Daniel, per your comment on @JRL's answer, you could probably get this working by spinning up a thread and waiting for a timeout.

Something like DetectBufferTimeout.java (untested) would do nicely.

I do, however, agree that spinning up this separate thread is a bit of a hack. Perhaps OnBufferingUpdateListener could make a guarantee as to how often it calls onBufferingUpdate() regardless of whether a change in the buffering progress has occurred so we can detect if we're getting the same value over and over.

查看更多
仙女界的扛把子
6楼-- · 2019-01-31 18:59

You can use a thread that checks the current position of the MediaPlayer. If the position doesnt change, you can conclude that the media is in buffering state. Here is the complete tutorial that i wrote: http://www.ottodroid.net/?p=260

查看更多
登录 后发表回答