自定义录像功能具体步骤大致为:
- 获取摄像头的ID(现在大部分相机都是前后两个摄像头,你需要根据需求打开前置摄像头或者后置摄像头),并且使用Camera对象将其打开。
- 获取一个SurfaceView对象,用于显示预览的图像。
- 当开始录制视频时(例如用户点击某个按钮),创建一个MediaRecorder对象
- 对MediaRecorder对象进行配置
- 录制视频
获取摄像头ID并打开摄像头
每个摄像头都有ID,分别代表为前置摄像头和后置摄像头,用户可以根据具体的业务需求开启相应的摄像头。
Android API文档中说,开启摄像头,是在UI线程中,并且需要一段时间。
如果你想在onCreate中开启,对好开辟一个线程去处理
或者将摄像头的开启放在onResume中
Getting an instance of the Camera object is the first step in the process of directly controlling the camera. As Android’s own Camera application does, the recommended way to access the camera is to open Camera on a separate thread that’s launched from onCreate(). This approach is a good idea since it can take a while and might bog down the UI thread. In a more basic implementation, opening the camera can be deferred to the onResume() method to facilitate code reuse and keep the flow of control simple.
获取前置摄像头(因为博主的项目只针对于前置摄像头开发):
private int FindFrontCamera(){
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount;camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
return camIdx;
}
}
return -1;
}
Camera.getNumberOfCameras()可访问的摄像机设备总数,如果没有摄像头,则为0。
Camera.CameraInfo是摄像头的信息,常量里面为CAMERA_FACING_BACK
、CAMERA_FACING_FRONT
后置摄像头和前置摄像头。
打开摄像头
mId = FindFrontCamera();
try {
mCamera = Camera.open(mId);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "摄像头正在使用", Toast.LENGTH_LONG).show();
return;
}
开启摄像头的时候应该进行异常检查
Caution: Always check for exceptions when using Camera.open(). Failing to check for exception