public class MyVioce extends AppCompatActivity implements SurfaceHolder.Callback {
private SurfaceView surfaceView;
private SurfaceHolder holder;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_vioce);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
holder = surfaceView.getHolder();
holder.addCallback(this);
holder.setFixedSize(320, 220);
}
public void play(View view) {
mediaPlayer.start();
}
public void pause(View view) {
mediaPlayer.pause();
}
public void stop(View view) {
mediaPlayer.stop();
}
/************
* 回调方法
********************/
@Override
public void surfaceCreated(SurfaceHolder holder) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(holder);
String path =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/2.mp4";
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mediaPlayer != null) {
/**
* 如果正在播放 ,则停止播放,并释放资源
*/
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
/**
* 如果正在播放 ,则停止播放,并释放资源
*/
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
}