Android 视频播放与进度条同步
首先获取视频播放长度来设置SeekBar的Max,videobBar.setMax(mediaPlayer.getDuration()),然后通过线程实时获取视频已经播放的时间来更新SeekBar,videobBar.setProgress(mediaPlayer.getCurrentPosition())思路就是这样,具体代码如下:
videobBar=(SeekBar)findViewById(R.id.seekBarPlayProgress);
surfaceView = (SurfaceView) findViewById(R.id.player);
surfaceView.getHolder().addCallback(new PlayCallback());
surfaceView.getHolder()
.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceView.getHolder().setFixedSize(surfaceView.getWidth(), surfaceView.getHeight());
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(surfaceView.getHolder());
try{
mediaPlayer.setDataSource("/sdcard/movie/自娱自乐_1.mp4");
mediaPlayer.prepare();
mediaPlayer.start();
videobBar.setMax(mediaPlayer.getDuration());
VideoThreed videoThreed=new VideoThreed();
videoThreed.start();
}
catch(Exception e)
{
Toast.makeText(this, "播放错误!", Toast.LENGTH_LONG).show();
}
//更新UI
Handler myHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
case PROGRESS_CHANGED:
videobBar.setProgress(mediaPlayer.getCurrentPosition());
break;
}
}
};
//视频进度条更新
class VideoThreed extends Thread
{
public void run()
{
while (!Thread.currentThread().isInterrupted())
{
if(mediaPlayer.getCurrentPosition()==mediaPlayer.getDuration())
{
return;
}
Message message = new Message();
message.what =PROGRESS_CHANGED;
VideoPlayer.this.myHandler.sendMessage(message);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
}