Can I record video with CameraX (Android Jetpack)?

Peter Fortuin picture Peter Fortuin · May 9, 2019 · Viewed 12.2k times · Source

Google has released the new CameraX library as part of Jetpack. It looks great for taking pictures, but my use case also require making video's. I tried googling for that, but couldn't find anything.

So, is it possible to record videos with the CameraX Jetpack library?

Answer

Patel Pinkal picture Patel Pinkal · May 9, 2019

Yes, we can record video using CameraX. I have tried to implement myself with help of Github demo for CameraX. Please refer below code may it helps you.

Config for Video in CameraX:

val videoCaptureConfig = VideoCaptureConfig.Builder().apply {
    setLensFacing(lensFacing)
    setTargetAspectRatio(screenAspectRatio)
    setTargetRotation(viewFinder.display.rotation)

}.build()

videoCapture = VideoCapture(videoCaptureConfig)

CameraX.bindToLifecycle(this, preview, imageCapture, videoCapture)

To Start video recording:

videoCapture?.startRecording(videoFile, object : VideoCapture.OnVideoSavedListener {
        override fun onVideoSaved(file: File?) {
            Log.i(javaClass.simpleName, "Video File : $file")
        }

        override fun onError(useCaseError: VideoCapture.UseCaseError?, message: String?, cause: Throwable?) {
            Log.i(javaClass.simpleName, "Video Error: $message")
        }

    })

To Stop video recording:

videoCapture?.stopRecording()

Same above I have mentioned in Github issue comment: https://github.com/android/camera/issues/2#issuecomment-490773932

Notes: There may be different in code to implementation of video recording using CameraX. Because this above code was developed by me without any other reference rather than Github Demo.

Please check important comment of Oscar Wahltinez on this answer as of 14 May 2019