Android MediaPlayer : How do i show a progress dia

2019-09-13 22:01发布

问题:

Im trying to play an mp3 audio from url. But when having slow network, player seems like not responding while buffering. So i need to add a progress dialog while buffering . Is it possible.? if yes can anyone help me to do.?

public class Player extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        Bundle b = new Bundle();
        b = getIntent().getExtras();
        final String url = b.getString("audio");
        Log.e("URL: ", url);
        final MediaPlayer mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            Log.e("preparing: ", url);
            mMediaPlayer.setDataSource(url);
            mMediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
        } catch (IOException e) {
            Toast.makeText(this, "mp3 not found", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

        //mp3 will be started after completion of preparing...
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer player) {
                int max = player.getDuration();
                Log.e("MAX", String.valueOf(max));
                player.start();
                Log.e("start: ", url);
            }
        });
    }
}

回答1:

You can show a seekbar, something like :

// In your onCreate(), add below at last .......
.
.
.
seekbar.setMax(mMediaPlayer.getDuration());
mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
    public void onBufferingUpdate(MediaPlayer mp, int percent) 
    {
        double ratio = percent / 100.0;
        bufferingLevel = (int)(mp.getDuration() * ratio);

        seekBar.setSecondaryProgress(bufferingLevel);
    }

}); 

Hope this helps !