Flashlight Camera2 API

泪湿孤枕 提交于 2019-12-01 09:06:53

问题


Can I use camera preview and flashlight at the same time in Android Camera2 API?

When I try use CameraManager.setTorchMode(String cameraId, boolean enabled) it's work fine when camera is not opened. But when Camera is open and I try setTorchMode I receive this exception:

CameraService: setTorchMode: torch mode of camera 0 is not available because camera is in use


回答1:


The error is indicating that the camera in question, is already in use.

You need to set the FLASH_MODE and CONTROL_AE_MODE accordingly.

mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
// Then Send request to current camera session
mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, null);



回答2:


No, they're mutually exclusive.

The camera device needs exclusive control of the flash while the camera is open, to ensure it can fire it as needed for pictures and so on.

If you want to turn on the torch while the camera is open, then use the camera API's flash mode setting. For the new camera2 API, that's setting the auto-exposure mode to just ON (CONTROL_AE_MODE_ON) and the flash mode to TORCH (FLASH_MODE_TORCH). And for the old camera API, that's Parameters.setFlashMode.




回答3:


I found solution:

CaptureRequest.Builder builder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
builder.set(CaptureRequest.FLASH_MODE, enable ? CameraMetadata.FLASH_MODE_TORCH : CameraMetadata.FLASH_MODE_OFF);
CaptureRequest request = builder.build();
cameraCaptureSession.capture(request, null, null);



回答4:


Setting both FLASH_MODE and AE_MODE is important. Below is the working piece of code:

public void toggleFlashMode(boolean enable){
try {
            if (mCameraType.equals(CameraType.BACK)) {
                if (enable) {
                    mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
                    mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
                } else {
                    mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
                    mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_OFF);
                }
                mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, null);
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
}


来源:https://stackoverflow.com/questions/33324647/flashlight-camera2-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!