Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I record video with CameraX (Android Jetpack)?

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?

like image 496
Peter Fortuin Avatar asked May 09 '19 07:05

Peter Fortuin


People also ask

Should I use CameraX?

For new apps, we recommend starting with CameraX. It provides a consistent, easy-to-use API that works across the vast majority of Android devices, with backward-compatibility to Android 5.0 (API level 21).


2 Answers

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

like image 89
Patel Pinkal Avatar answered Oct 12 '22 13:10

Patel Pinkal


This is my solution

//Versions in Gradle def camerax_version = "1.0.0-beta06" def camera_extensions = "1.0.0-alpha13"  private lateinit var videoCapture: VideoCapture private lateinit var viewFinder: PreviewView private lateinit var outputDirectory: File private var lensFacing: Int = CameraSelector.LENS_FACING_FRONT   private val executor = Executors.newSingleThreadExecutor() private var isRecording = false private var camera: Camera? = null private lateinit var cameraProviderFuture: ListenableFuture<ProcessCameraProvider>   //onCreate viewFinder = preview_video_view     runWithPermissions(*permissions) {         startCamera(view.context)         initClicks()     }   @SuppressLint("RestrictedApi", "UnsafeExperimentalUsageError") private fun startCamera(context: Context) {     outputDirectory = getOutputDirectory(context)     cameraProviderFuture = ProcessCameraProvider.getInstance(context)      val cameraSelector = CameraSelector.Builder().requireLensFacing(lensFacing).build()      // Create a configuration object for the video use case     val videoCaptureConfig = VideoCaptureConfig.Builder().apply {         setTargetRotation(viewFinder.display.rotation)         setCameraSelector(cameraSelector)     }       //CameraX.initialize(context, this.cameraXConfig)       videoCapture = VideoCapture(videoCaptureConfig.useCaseConfig)      val preview: Preview = Preview.Builder().apply {         setTargetAspectRatio(AspectRatio.RATIO_16_9)         setTargetRotation(viewFinder.display.rotation)     }.build()     preview.setSurfaceProvider(viewFinder.createSurfaceProvider())      cameraProviderFuture.addListener(Runnable {         val cameraProvider = cameraProviderFuture.get()         camera = cameraProvider.bindToLifecycle(             viewLifecycleOwner,             cameraSelector,             preview,             videoCapture         )              }, ContextCompat.getMainExecutor(context)) }  @SuppressLint("RestrictedApi") private fun startRecording() {     val file = createFile(         outputDirectory,         FILENAME,         VIDEO_EXTENSION     )      videoCapture.startRecording(         file,         executor,         object : VideoCapture.OnVideoSavedCallback {             override fun onVideoSaved(file: File) {                 Handler(Looper.getMainLooper()).post {                     showMessage(file.name + " is saved")                 }             }              override fun onError(videoCaptureError: Int, message: String, cause: Throwable?) {                 Handler(Looper.getMainLooper()).post {                     showMessage(videoCaptureError.toString() + " " + message)                 }             }         }     ) }  @SuppressLint("RestrictedApi") private fun stopRecording() {     videoCapture.stopRecording() }   override fun getCameraXConfig(): CameraXConfig {     return Camera2Config.defaultConfig() }  companion object {     private const val FILENAME = "yyyy_MM_dd_HH_mm_ss"     private const val VIDEO_EXTENSION = ".mp4"      private val permissions = arrayOf(         Manifest.permission.WRITE_EXTERNAL_STORAGE,         Manifest.permission.READ_EXTERNAL_STORAGE,         Manifest.permission.CAMERA,         Manifest.permission.RECORD_AUDIO     )      fun getOutputDirectory(context: Context): File {         val appContext = context.applicationContext         val mediaDir = appContext.externalMediaDirs.firstOrNull()?.let {             File(it, appContext.resources.getString(R.string.app_name)).apply { mkdirs() }         }         return if (mediaDir != null && mediaDir.exists()) mediaDir else appContext.filesDir     }      fun createFile(baseFolder: File, format: String, extension: String) =         File(baseFolder, SimpleDateFormat(format, Locale.US)             .format(System.currentTimeMillis()) + extension) } 
like image 35
Sergei Maleev Avatar answered Oct 12 '22 12:10

Sergei Maleev