打开相机
/**
* open Camera
*/
void doOpenCamera(CameraOpenOverCallback callback) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (!CheckPermission.isCameraUseable(SELECTED_CAMERA) && this.errorLisenter != null) {
this.errorLisenter.onError();
return;
}
}
if (mCamera == null) {
openCamera(SELECTED_CAMERA);
}
callback.cameraHasOpened();
}
private synchronized void openCamera(int id) {
try {
this.mCamera = Camera.open(id);
} catch (Exception var3) {
var3.printStackTrace();
if (this.errorLisenter != null) {
this.errorLisenter.onError();
}
}
if (Build.VERSION.SDK_INT > 17 && this.mCamera != null) {
try {
this.mCamera.enableShutterSound(false);
} catch (Exception e) {
e.printStackTrace();
Log.e("CJT", "enable shutter sound faild");
}
}
}
添加预览
/**
* doStartPreview
*/
public void doStartPreview(SurfaceHolder holder, float screenProp) {
if (isPreviewing) {
LogUtil.i("doStartPreview isPreviewing");
}
if (this.screenProp < 0) {
this.screenProp = screenProp;
}
if (holder == null) {
return;
}
this.mHolder = holder;
if (mCamera != null) {
try {
mParams = mCamera.getParameters();
Camera.Size previewSize = CameraParamUtil.getInstance().getPreviewSize(mParams
.getSupportedPreviewSizes(), 1000, screenProp);
Camera.Size pictureSize = CameraParamUtil.getInstance().getPictureSize(mParams
.getSupportedPictureSizes(), 1200, screenProp);
mParams.setPreviewSize(previewSize.width, previewSize.height);
preview_width = previewSize.width;
preview_height = previewSize.height;
mParams.setPictureSize(pictureSize.width, pictureSize.height);
if (CameraParamUtil.getInstance().isSupportedFocusMode(
mParams.getSupportedFocusModes(),
Camera.Parameters.FOCUS_MODE_AUTO)) {
mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
if (CameraParamUtil.getInstance().isSupportedPictureFormats(mParams.getSupportedPictureFormats(),
ImageFormat.JPEG)) {
mParams.setPictureFormat(ImageFormat.JPEG);
mParams.setJpegQuality(100);
}
mCamera.setParameters(mParams);
mParams = mCamera.getParameters();
mCamera.setPreviewDisplay(holder); //SurfaceView
mCamera.setDisplayOrientation(cameraAngle);//浏览角度
mCamera.setPreviewCallback(this); //每一帧回调
mCamera.startPreview();//启动浏览
isPreviewing = true;
Log.i(TAG, "=== Start Preview ===");
} catch (IOException e) {
e.printStackTrace();
}
}
}
停止预览
/**
* 停止预览
*/
public void doStopPreview() {
if (null != mCamera) {
try {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
//这句要在stopPreview后执行,不然会卡顿或者花屏
mCamera.setPreviewDisplay(null);
isPreviewing = false;
Log.i(TAG, "=== Stop Preview ===");
} catch (IOException e) {
e.printStackTrace();
}
}
}
销毁Camera
/**
* 销毁Camera
*/
void doDestroyCamera() {
errorLisenter = null;
if (null != mCamera) {
try {
mCamera.setPreviewCallback(null);
mSwitchView = null;
mFlashLamp = null;
mCamera.stopPreview();
//这句要在stopPreview后执行,不然会卡顿或者花屏
mCamera.setPreviewDisplay(null);
mHolder = null;
isPreviewing = false;
mCamera.release();
mCamera = null;
// destroyCameraInterface();
Log.i(TAG, "=== Destroy Camera ===");
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "=== Camera Null===");
}
}
拍照
/**
* 拍照
*/
private int nowAngle;
public void takePicture(final TakePictureCallback callback) {
if (mCamera == null) {
return;
}
switch (cameraAngle) {
case 90:
nowAngle = Math.abs(angle + cameraAngle) % 360;
break;
case 270:
nowAngle = Math.abs(cameraAngle - angle);
break;
}
//
Log.i("CJT", angle + " = " + cameraAngle + " = " + nowAngle);
mCamera.takePicture(null, null, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Matrix matrix = new Matrix();
if (SELECTED_CAMERA == CAMERA_POST_POSITION) {
matrix.setRotate(nowAngle);
} else if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) {
matrix.setRotate(360 - nowAngle);
matrix.postScale(-1, 1);
}
bitmap = createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
if (callback != null) {
if (nowAngle == 90 || nowAngle == 270) {
callback.captureResult(bitmap, true);
} else {
callback.captureResult(bitmap, false);
}
}
}
});
}
启动录像
//启动录像
public void startRecord(Surface surface, float screenProp, ErrorCallback callback) {
mCamera.setPreviewCallback(null);
final int nowAngle = (angle + 90) % 360;
//获取第一帧图片
Camera.Parameters parameters = mCamera.getParameters();
int width = parameters.getPreviewSize().width;
int height = parameters.getPreviewSize().height;
YuvImage yuv = new YuvImage(firstFrame_data, parameters.getPreviewFormat(), width, height, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuv.compressToJpeg(new Rect(0, 0, width, height), 50, out);
byte[] bytes = out.toByteArray();
videoFirstFrame = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Matrix matrix = new Matrix();
if (SELECTED_CAMERA == CAMERA_POST_POSITION) {
matrix.setRotate(nowAngle);
} else if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) {
matrix.setRotate(270);
}
videoFirstFrame = createBitmap(videoFirstFrame, 0, 0, videoFirstFrame.getWidth(), videoFirstFrame
.getHeight(), matrix, true);
if (isRecorder) {
return;
}
if (mCamera == null) {
openCamera(SELECTED_CAMERA);
}
if (mediaRecorder == null) {
mediaRecorder = new MediaRecorder();
}
if (mParams == null) {
mParams = mCamera.getParameters();
}
List<String> focusModes = mParams.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
mCamera.setParameters(mParams);
mCamera.unlock();
mediaRecorder.reset();
mediaRecorder.setCamera(mCamera);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
Camera.Size videoSize;
if (mParams.getSupportedVideoSizes() == null) {
videoSize = CameraParamUtil.getInstance().getPreviewSize(mParams.getSupportedPreviewSizes(), 600,
screenProp);
} else {
videoSize = CameraParamUtil.getInstance().getPreviewSize(mParams.getSupportedVideoSizes(), 600,
screenProp);
}
Log.i(TAG, "setVideoSize width = " + videoSize.width + "height = " + videoSize.height);
if (videoSize.width == videoSize.height) {
mediaRecorder.setVideoSize(preview_width, preview_height);
} else {
mediaRecorder.setVideoSize(videoSize.width, videoSize.height);
}
// if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) {
// mediaRecorder.setOrientationHint(270);
// } else {
// mediaRecorder.setOrientationHint(nowAngle);
//// mediaRecorder.setOrientationHint(90);
// }
if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) {
//手机预览倒立的处理
if (cameraAngle == 270) {
//横屏
if (nowAngle == 0) {
mediaRecorder.setOrientationHint(180);
} else if (nowAngle == 270) {
mediaRecorder.setOrientationHint(270);
} else {
mediaRecorder.setOrientationHint(90);
}
} else {
if (nowAngle == 90) {
mediaRecorder.setOrientationHint(270);
} else if (nowAngle == 270) {
mediaRecorder.setOrientationHint(90);
} else {
mediaRecorder.setOrientationHint(nowAngle);
}
}
} else {
mediaRecorder.setOrientationHint(nowAngle);
}
if (DeviceUtil.isHuaWeiRongyao()) {
mediaRecorder.setVideoEncodingBitRate(4 * 100000);
} else {
mediaRecorder.setVideoEncodingBitRate(mediaQuality);
}
mediaRecorder.setPreviewDisplay(surface);
videoFileName = "video_" + System.currentTimeMillis() + ".mp4";
if (saveVideoPath.equals("")) {
saveVideoPath = Environment.getExternalStorageDirectory().getPath();
}
videoFileAbsPath = saveVideoPath + File.separator + videoFileName;
mediaRecorder.setOutputFile(videoFileAbsPath);
try {
mediaRecorder.prepare();
mediaRecorder.start();
isRecorder = true;
} catch (IllegalStateException e) {
e.printStackTrace();
Log.i("CJT", "startRecord IllegalStateException");
if (this.errorLisenter != null) {
this.errorLisenter.onError();
}
} catch (IOException e) {
e.printStackTrace();
Log.i("CJT", "startRecord IOException");
if (this.errorLisenter != null) {
this.errorLisenter.onError();
}
} catch (RuntimeException e) {
Log.i("CJT", "startRecord RuntimeException");
}
}
停止录像
//停止录像
public void stopRecord(boolean isShort, StopRecordCallback callback) {
if (!isRecorder) {
return;
}
if (mediaRecorder != null) {
mediaRecorder.setOnErrorListener(null);
mediaRecorder.setOnInfoListener(null);
mediaRecorder.setPreviewDisplay(null);
try {
mediaRecorder.stop();
} catch (RuntimeException e) {
e.printStackTrace();
mediaRecorder = null;
mediaRecorder = new MediaRecorder();
} finally {
if (mediaRecorder != null) {
mediaRecorder.release();
}
mediaRecorder = null;
isRecorder = false;
}
if (isShort) {
if (FileUtil.deleteFile(videoFileAbsPath)) {
callback.recordResult(null, null);
}
return;
}
doStopPreview();
String fileName = saveVideoPath + File.separator + videoFileName;
callback.recordResult(fileName, videoFirstFrame);
}
}
对焦
public void handleFocus(final Context context, final float x, final float y, final FocusCallback callback) {
if (mCamera == null) {
return;
}
final Camera.Parameters params = mCamera.getParameters();
Rect focusRect = calculateTapArea(x, y, 1f, context);
mCamera.cancelAutoFocus();
if (params.getMaxNumFocusAreas() > 0) {
List<Camera.Area> focusAreas = new ArrayList<>();
focusAreas.add(new Camera.Area(focusRect, 800));
params.setFocusAreas(focusAreas);
} else {
Log.i(TAG, "focus areas not supported");
callback.focusSuccess();
return;
}
final String currentFocusMode = params.getFocusMode();
try {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
mCamera.setParameters(params);
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
if (success || handlerTime > 10) {
Camera.Parameters params = camera.getParameters();
params.setFocusMode(currentFocusMode);
camera.setParameters(params);
handlerTime = 0;
callback.focusSuccess();
} else {
handlerTime++;
handleFocus(context, x, y, callback);
}
}
});
} catch (Exception e) {
Log.e(TAG, "autoFocus failer");
}
}