使用SurfaceView+MediaPlayer+SeekBar實現視屏播放器
阿新 • • 發佈:2019-02-19
class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SeekBar sb_main_bar;
private SurfaceView sv_main_surface;
/*
使用SurfaceView+MediaPlayer+SeekBar實現視屏播放器
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState) ;
setContentView(R.layout.activity_main);
sb_main_bar = (SeekBar) findViewById(R.id.sb_main_bar);//獲取SeekBar的id
sv_main_surface = (SurfaceView) findViewById(R.id.sv_main_surface);//獲取SurfaceView的id
//給進度條設定滑動的監聽
sb_main_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress=seekBar.getProgress();
//進度條在當前位置播放
mediaPlayer.seekTo(progress);
}
});
}
//播放按鈕
public void isPlayOrPause(View view){
final ImageButton imageButton= (ImageButton) view;
if(mediaPlayer==null){
mediaPlayer=new MediaPlayer();
//設定音源
try {
mediaPlayer.setDataSource(this, Uri.parse("file://手機儲存/DCIM/Camera/lala.mp4"));
//準備
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
//將媒體播放器捕捉的畫面展示到SurfaceView
mediaPlayer.setDisplay(sv_main_surface.getHolder());
mediaPlayer.start();
imageButton.setImageResource(android.R.drawable.ic_media_pause);
//獲取音樂的總時長
int duration=mediaPlayer.getDuration();
//將進度條設定最大值為:音樂的總時長
sb_main_bar.setMax(duration);
new MyThread().start();
}else if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
imageButton.setImageResource(android.R.drawable.ic_media_play);
}else{
mediaPlayer.start();
imageButton.setImageResource(android.R.drawable.ic_media_pause);
}
}
class MyThread extends Thread{
@Override
public void run() {
super.run();
while(sb_main_bar.getProgress()<=sb_main_bar.getMax()){
//獲取音樂當前播放的位置
int position=mediaPlayer.getCurrentPosition();
sb_main_bar.setProgress(position);
}
}
}
}