最近本身開發的應用須要個視頻演示功能,就想到了用VideoView來播放百度雲上存放的視頻,可是Android提供的MediaController知足不了需求。因此就考慮本身寫個視頻控制器,看了下VideoView的API發現有getBufferPercentage()和getCurrentPosition ()來獲取當前緩衝區的大小和當前播放位置,沒發現有監聽緩衝區的方法。只能本身寫個定時器來監聽了。ide
1 private Handler handler = new Handler(); 2 private Runnable run = new Runnable() { 3 int buffer, currentPosition, duration; 4 public void run() { 5 // 得到當前播放時間和當前視頻的長度 6 currentPosition = videoView.getCurrentPosition(); 7 duration = videoView.getDuration(); 8 int time = ((currentPosition * 100) / duration); 9 // 設置進度條的主要進度,表示當前的播放時間 10 seekBar.setProgress(time); 11 // 設置進度條的次要進度,表示視頻的緩衝進度 12 buffer = videoView.getBufferPercentage(); 13 seekBar.setSecondaryProgress(percent); 14 15 handler.postDelayed(run, 1000); 16 } 17 };
設置爲每1000毫秒獲取一次緩衝區和當前播放位置的狀態。由於沒有調用start(),因此實際handler把run加到了消息隊列裏等主線程來執行,直接在run裏面更新UI就能夠。post
在videoView.start();後面加入handler.post(run);就能夠啓用定時器了。或者在設置了videoView.setOnPreparedListener(this);後放進onPrepared()方法裏,等視頻文件加載完畢自動啓動。this
特別注意一下記得在視頻播放器退出時用handler.removeCallbacks(run);來銷燬線程。重寫Activity的onDestroy()方法spa
1 @Override 2 protected void onDestroy() { 3 handler.removeCallbacks(run); 4 super.onDestroy(); 5 }
後來查看資料的時候發現有另一種方法,只要拿到MediaPlayer對象再設置setOnBufferingUpdateListener()監聽器就能監聽緩衝區的狀態了。線程
1 public class TestActivity extends Activity implements OnPreparedListener{ 2 private TextView videoback; 3 private VideoView videoView; 4 5 @Override 6 protected void onCreate(Bundle savedInstanceState) { 7 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.test); 10 seekBar = (SeekBar) findViewById(R.id.test_seekbar); 11 videoView = (VideoView) findViewById(R.id.test_video); 12 videoView.setOnPreparedListener(this); 13 } 14 15 public void onPrepared(MediaPlayer mp) { 16 mp.setOnBufferingUpdateListener(new OnBufferingUpdateListener() { 17 int currentPosition, duration; 18 public void onBufferingUpdate(MediaPlayer mp, int percent) { 19 // 得到當前播放時間和當前視頻的長度 20 currentPosition = videoView.getCurrentPosition(); 21 duration = videoView.getDuration(); 22 int time = ((currentPosition * 100) / duration); 23 // 設置進度條的主要進度,表示當前的播放時間 24 SeekBar seekBar = new SeekBar(EsActivity.this); 25 seekBar.setProgress(time); 26 // 設置進度條的次要進度,表示視頻的緩衝進度 27 seekBar.setSecondaryProgress(percent); 28 } 29 }); 30 } 31 }