30

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

那么,是否可以使用 CameraX Jetpack 库录制视频?

4

6 回答 6

26

是的,我们可以使用CameraX. 我试图在 Github demo for CameraX的帮助下实现自己。请参考下面的代码可能对您有所帮助。

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 日对此答案的重要评论

于 2019-05-09T09:05:40.570 回答
9

这是我的解决方案

//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)
}
于 2020-07-15T10:33:43.123 回答
8

更新 Patel Pinkal 的答案。发布测试版后,我们不能再使用 VideoCaptureConfig.Builder() 了,取而代之的是:

 videoCapture = VideoCapture.Builder().apply {
     // init config here
 }.build()
于 2020-08-05T10:03:50.673 回答
6

截至 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 仍受限制且仍可能更改。

于 2021-04-27T14:24:23.230 回答
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")
            }
        }
于 2021-02-05T11:07:20.943 回答
0

CameraX VideoCapture 用例在 camera-video 中实现,自1.1.0-alpha30发布。请参阅以下内容:

详情。

于 2021-11-20T01:41:00.067 回答