#java #android #kotlin #android-camera #android-camera2
#java #Android #kotlin #android-камера #android-camera2
Вопрос:
Я написал базовый код для использования API Camera 2. И теперь мне нужен код для программной записи видео одним нажатием кнопки
Как вы можете видеть ниже, я использую Kotlin для CameraFragment и Java для MainActivity
CameraFragment.kt:
class CameraFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallback {
......
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_camera, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewFinder = view.findViewById(R.id.view_finder)
viewFinder.holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceChanged(
holder: SurfaceHolder?,
format: Int,
width: Int,
height: Int) = Unit
override fun surfaceDestroyed(holder: SurfaceHolder?) = Unit
override fun surfaceCreated(holder: SurfaceHolder?) {
Log.d(TAG, "View finder size: ${viewFinder.width} x ${viewFinder.height}")
view.post { getPermissions() }
}
})
}
........
override fun onStop() {
super.onStop()
try { camera.close() } catch (exc: Throwable) {}
}
override fun onDestroy() {
super.onDestroy()
cameraThread.quitSafely()
}
private suspend fun openCamera(
manager: CameraManager,
cameraId: String,
handler: Handler? = null
): CameraDevice = suspendCancellableCoroutine { cont ->
val permission = ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.CAMERA
)
assert(permission != PackageManager.PERMISSION_GRANTED)
manager.openCamera(cameraId, object : CameraDevice.StateCallback() {
override fun onOpened(camera: CameraDevice) = cont.resume(camera)
override fun onDisconnected(camera: CameraDevice) {
Log.w(TAG, "Camera $cameraId has been disconnected")
requireActivity().finish()
}
override fun onError(camera: CameraDevice, error: Int) {
}
}, handler)
}
private fun initializeCamera() = lifecycleScope.launch(Dispatchers.Main) {
camera = openCamera(cameraManager, cameraManager.cameraIdList.first(), cameraHandler)
val targets = listOf(viewFinder.holder.surface)
session = createCaptureSession(camera, targets, cameraHandler)
captureRequest = camera
.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
.apply { addTarget(viewFinder.holder.surface) }
session.setRepeatingRequest(captureRequest.build(), null, cameraHandler)
}
private suspend fun createCaptureSession(
device: CameraDevice,
targets: List<Surface>,
handler: Handler? = null
): CameraCaptureSession = suspendCoroutine { cont ->
device.createCaptureSession(targets, object: CameraCaptureSession.StateCallback() {
override fun onConfigureFailed(session: CameraCaptureSession) {
val exc = RuntimeException("Camera ${device.id} session configuration failed")
Log.e(TAG, exc.message, exc)
cont.resumeWithException(exc)
}
override fun onConfigured(session: CameraCaptureSession) {
cont.resume(session)
}
}, handler)
}
}
Вот код, который я использую для инициализации фрагмента камеры
MainActivity.java:
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.camera_fragment);
if (fragment == null) {
} else {
this.cameraFragment = (CameraFragment) fragment;
}
Пожалуйста, поделитесь необходимым кодом для программной записи видео
Ответ №1:
Взгляните на образец Camera2Video из Google.