Android开发之视频录制
转载▼
要使用视频录制功能,要用到MediaRecorder这个类,以及SurfaceView组建
public class MainActivity extends Activity {
public static final String TAG = "MainActivity";
@Override
protected void onDestroy() {
mediaRecorder.release();
super.onDestroy();
}
private SurfaceView surfaceView;
private Button btn_start;
private Button btn_stop;
private MediaRecorder mediaRecorder;
private boolean record;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mediaRecorder = new MediaRecorder();
surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
this.surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
this.surfaceView.getHolder().setFixedSize(320, 240);//设置分辨率
btn_start = (Button) findViewById(R.id.btn_start);
btn_stop=(Button) findViewById(R.id.btn_stop);
ClickListener clickListener = new ClickListener();
btn_start.setOnClickListener(clickListener);
btn_stop.setOnClickListener(clickListener);
}
private final class ClickListener implements View.OnClickListener{
public void onClick(View v) {
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Toast.makeText(MainActivity.this, "SD卡不存在或写保护!", 1).show();
return ;
}
try {
switch(v.getId()){
case R.id.btn_start:
mediaRecorder.reset();
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); //从照相机采集视频
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setVideoSize(320, 240);
mediaRecorder.setVideoFrameRate(3); //每秒3帧
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); //设置视频编码方式
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
File videoFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis()+".3gp");
mediaRecorder.setOutputFile(videoFile.getAbsolutePath());
mediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
mediaRecorder.prepare();//预期准备
mediaRecorder.start();//开始刻录
record = true;
break;
case R.id.btn_stop:
if(record){
mediaRecorder.stop();
record = false;
}
break;
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}
}