public class MainActivity extends Activity implements OnClickListener{
private EditText et_path;
private Button bt_play, bt_replay, bt_pause, bt_stop;
private MediaPlayer mp;
private SurfaceView sf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText)findViewById(R.id.et_path);
sf = (SurfaceView)findViewById(R.id.sf);
bt_play = (Button)findViewById(R.id.bt_play);
bt_pause = (Button)findViewById(R.id.bt_pause);
bt_replay = (Button)findViewById(R.id.bt_replay);
bt_stop = (Button)findViewById(R.id.bt_stop);
bt_play.setOnClickListener(this);
bt_pause.setOnClickListener(this);
bt_replay.setOnClickListener(this);
bt_stop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bt_play:
play();
break;
case R.id.bt_pause:
pause();
break;
case R.id.bt_replay:
replay();
break;
case R.id.bt_stop:
stop();
break;
}
}
public void play(){
String path = et_path.getText().toString().trim();
File file = new File(path);
if(file.exists()&&file.length()>0){
try {
//Uri myUri = Uri.parse("/data/data/com.example.player/a.mp3"); // initialize Uri here
if(mp == null){
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
//这只Video影片以SurfaceHolder播放
mp.setDisplay(sf.getHolder());
mp.setDataSource(path);
mp.prepare();
mp.start();
}
} catch (Exception e) {
Toast.makeText(this, "播放失败", 1).show();
e.printStackTrace();
}
}else{
Toast.makeText(this, "音频文件不存在", 1).show();
}
/*if(mp == null){
mp = new MediaPlayer();
mp.create(getApplicationContext(), R.raw.a);
mp.start();
}*/
}
public void pause(){
//mp.pause();
if((bt_pause.getText().toString().trim()).equals("暂停")){
if(mp!=null&&mp.isPlaying()){
bt_pause.setText("继续");
mp.pause();
}
}else{
bt_pause.setText("暂停");
mp.start();
}
}
/**
* 重新播放
*/
public void replay(){
if(mp!=null&&mp.isPlaying()){
mp.seekTo(0);
return;
}
play();
}
/**
* 停止播放
*/
public void stop(){
if(mp!=null&&mp.isPlaying()){
mp.stop();
mp.release();
mp = null;
}
}
}
video播放器
最新推荐文章于 2022-05-06 03:11:26 发布