我可以使用CameraX(Android Jetpack)录制视频吗?

时间:2019-05-09 07:51:42

标签: android android-jetpack android-camerax

Google已将新的CameraX库发布为Jetpack的一部分。它看起来很适合拍照,但我的用例还需要制作视频。我为此尝试使用Google搜索,但找不到任何东西。

那么,可以用CameraX Jetpack库录制视频吗?

5 个答案:

答案 0 :(得分:7)

这是我的解决方法

//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)
}

答案 1 :(得分:4)

更新Patel Pinkal的答案。 Beta发布后,我们不能再使用VideoCaptureConfig.Builder()了,而是使用类似的东西:

 videoCapture = VideoCapture.Builder().apply {
     // init config here
 }.build()

答案 2 :(得分:4)

截至 2021 年 4 月

val videoCapture = VideoCapture.Builder().build()
val outputDirectory = getOutputDirectory()


fun getOutputDirectory(): File {
        val mediaDir = externalMediaDirs.firstOrNull()?.let {
            File(it, resources.getString(R.string.app_name)).apply { mkdirs() } }
        return if (mediaDir != null && mediaDir.exists())
            mediaDir else filesDir
}


@SuppressLint("RestrictedApi")
    private fun startRecording() {
        val videoFile = File(
            outputDirectory,
            SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS", Locale.US
            ).format(System.currentTimeMillis()) + ".mp4")
        val outputOptions = VideoCapture.OutputFileOptions.Builder(videoFile).build()

        videoCapture?.startRecording(outputOptions, ContextCompat.getMainExecutor(this), object: VideoCapture.OnVideoSavedCallback {
            override fun onError(videoCaptureError: Int, message: String, cause: Throwable?) {
                Log.e(TAG, "Video capture failed: $message")
            }

            override fun onVideoSaved(outputFileResults: VideoCapture.OutputFileResults) {
                val savedUri = Uri.fromFile(videoFile)
                val msg = "Video capture succeeded: $savedUri"
                Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                Log.d(TAG, msg)
            }
        })
    }

@SuppressLint("RestrictedApi")
    private fun stopRecording() {
        videoCapture?.stopRecording()
    }

请注意,此 API 仍然受到限制并且可能会发生变化。

答案 3 :(得分:3)

是的,我们可以使用CameraX录制视频。我尝试在CameraX的Github演示的帮助下实现自己。请参考下面的代码,可能对您有帮助。

在CameraX中配置视频:

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

}.build()

videoCapture = VideoCapture(videoCaptureConfig)

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

开始录制视频:

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")
        }

    })

要停止录像:

videoCapture?.stopRecording()

与我在Github问题评论中提到的相同:https://github.com/android/camera/issues/2#issuecomment-490773932

  

注意:与使用CameraX进行视频录制的代码可能有所不同。因为上面的代码是我开发的,除了Github Demo之外,我没有其他参考。

     

请查看Oscar Wahltinez对此答案的重要评论,截至2019年5月14日

答案 4 :(得分:0)

关于 Sergei 的回答,videoCapture.startRecording() 接收 VideoCapture.OutputFileOptions 而不是 camerax_version = '1.0.0-rc01' 的文件,所以它应该用作:

videoCapture.startRecording(
        VideoCapture.OutputFileOptions.Builder(file).build(),
        executor,
        object : VideoCapture.OnVideoSavedCallback {
            override fun onVideoSaved(outputFileResults: VideoCapture.OutputFileResults) {
                TODO("Not yet implemented")
            }

            override fun onError(videoCaptureError: Int, message: String, cause: Throwable?) {
                TODO("Not yet implemented")
            }
        }