最近自己開發的應用需要個視頻演示功能,就想到了用VideoView來播放百度雲上存放的視頻,但是Android提供的MediaController滿足不了需求。所以就考慮自己寫個視頻控制器,看了下VideoView的API發現有getBufferPercentage()和getCurrentPosition ()來獲取當前緩沖區的大小和當前播放位置,沒發現有監聽緩沖區的方法。只能自己寫個定時器來監聽了。
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就可以。
在videoView.start();后面加入handler.post(run);就可以啟用定時器了。或者在設置了videoView.setOnPreparedListener(this);后放進onPrepared()方法里,等視頻文件加載完畢自動啟動。
特別注意一下記得在視頻播放器退出時用handler.removeCallbacks(run);來銷毀線程。重寫Activity的onDestroy()方法
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 }