public class MainActivity extends Activity {
private SurfaceView surfaceView;
private RelativeLayout layout;
private Button recordbutton;
private Button stopbutton;
private MediaRecorder mediaRecorder;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//设置窗口特性没有标题
//设置窗口全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView);
//设置对数据不用缓存直接输出到SurfaceView上
surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//设置屏幕大小
surfaceView.getHolder().setFixedSize(176, 144);
//设置屏幕常亮
surfaceView.getHolder().setKeepScreenOn(true);
layout = (RelativeLayout) this.findViewById(R.id.layout);
recordbutton = (Button) this.findViewById(R.id.recordbutton);
stopbutton = (Button) this.findViewById(R.id.stopbutton);
}
@Override
//处理屏幕触摸事件
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
layout.setVisibility(ViewGroup.VISIBLE);
}
return super.onTouchEvent(event);
}
//刻录方法
public void record(View v){
switch (v.getId()) {
case R.id.recordbutton:
try{
File videoFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis()+ ".3gp");
mediaRecorder = new MediaRecorder();//创建刻录对象
//设置音频来源
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//设置视频来源
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
//设置文件输出格式
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
//设置视频大小
mediaRecorder.setVideoSize(320, 240);
//设置每秒多少张
mediaRecorder.setVideoFrameRate(5);
//设置音频编码
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
//设置视频编码
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
//设置文件输出方向
mediaRecorder.setOutputFile(videoFile.getAbsolutePath());
//设置预览到那块
mediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
//开始准备
mediaRecorder.prepare();
//开始刻录
mediaRecorder.start();
}catch (Exception e) {
e.printStackTrace();
}
recordbutton.setEnabled(false);
stopbutton.setEnabled(true);
break;
case R.id.stopbutton:
if(mediaRecorder!=null){
//结束刻录
mediaRecorder.stop();
//释放资源
mediaRecorder.release();
mediaRecorder = null;
}
recordbutton.setEnabled(true);
stopbutton.setEnabled(false);
break;
}
}
}