首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我可以用CameraX (Android Jetpack)录制视频吗?

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

Stack Overflow用户
提问于 2019-05-09 15:51:42
回答 6查看 17.9K关注 0票数 30

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

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

EN

回答 6

Stack Overflow用户

发布于 2019-05-09 17:05:41

是的,我们可以使用CameraX录制视频。我尝试在CameraX的Github demo的帮助下实现自己的功能。请参考下面的代码,希望它能对你有所帮助。

CameraX中视频的配置:

代码语言:javascript
复制
val videoCaptureConfig = VideoCaptureConfig.Builder().apply {
    setLensFacing(lensFacing)
    setTargetAspectRatio(screenAspectRatio)
    setTargetRotation(viewFinder.display.rotation)

}.build()

videoCapture = VideoCapture(videoCaptureConfig)

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

开始录制视频的

代码语言:javascript
复制
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")
        }

    })

停止视频录制的

代码语言:javascript
复制
videoCapture?.stopRecording()

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

备注:使用CameraX实现视频录制的代码可能有所不同。因为上面的代码是由我开发的,没有任何其他参考,而不是Github Demo。

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

票数 26
EN

Stack Overflow用户

发布于 2020-07-15 18:33:43

这是我的解决方案

代码语言:javascript
复制
//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)
}
票数 9
EN

Stack Overflow用户

发布于 2020-08-05 18:03:51

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

代码语言:javascript
复制
 videoCapture = VideoCapture.Builder().apply {
     // init config here
 }.build()
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56054647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档