Android 使用 CameraX 实现拍照和录制视频

字节流动

共 6711字,需浏览 14分钟

 ·

2022-05-09 22:22

原文链接: https://juejin.cn/post/6862180757314469901

AndroidX是Jetpack包下的组件,谷歌帮你考虑好了很多细节,用就完事了。这些细节想自己设置的话也可以,不设置使用默认值照样很舒服。

导包

implementation "androidx.camera:camera-camera2:1.0.0-beta07"
implementation "androidx.camera:camera-view:1.0.0-alpha14"
implementation "androidx.camera:camera-extensions:1.0.0-alpha14"
implementation "androidx.camera:camera-lifecycle:1.0.0-beta07"

请求权限

Manifestmanifest 节点下中加入以下内容:


<uses-permission android:name="android.permission.CAMERA" />

<uses-feature android:name="android.hardware.camera.any" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.RECORD_AUDIO" />

Android Q适配

manifest 标签里面加入一条属性:

 android:requestLegacyExternalStorage="true"

画黄线不理,如果不加这句,在Android Q上会无法往相册存储文件。

创建预览布局

这里参考官方Demo的写法,最底部图层是一个PreviewView用来预览,上层放两个按钮,一个用来拍照,一个用来录像。


<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/btnStartVideo"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginBottom="50dp"
        android:elevation="2dp"
        android:scaleType="fitCenter"
        android:text="Start Video"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/camera_capture_button" />


    <Button
        android:id="@+id/camera_capture_button"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:elevation="2dp"
        android:scaleType="fitCenter"
        android:text="Take Photo"
        app:layout_constraintBottom_toBottomOf="@+id/btnStartVideo"
        app:layout_constraintEnd_toStartOf="@id/btnStartVideo"
        app:layout_constraintStart_toStartOf="parent" />


    <androidx.camera.view.PreviewView
        android:id="@+id/viewFinder"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


androidx.constraintlayout.widget.ConstraintLayout>

Activity中申请权限

声明权限列表

companion object {
    private const val REQUEST_CODE_PERMISSIONS = 10
    private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)
}

判断当前是否已有权限的方法

private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
    ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
}

onCreate 里开始主要逻辑。如果已有权限,开启相机预览。

 if (allPermissionsGranted()) {
      startCamera()
else {
      ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
}

在请求权限返回的时候,判断是否已有权限,如果有了就可以开启预览了

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
    if (requestCode == REQUEST_CODE_PERMISSIONS) {
        if (allPermissionsGranted()) {
            startCamera()
        } else {
            Toast.makeText(this"Permissions not granted by the user.", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
}

声明全局变量

private lateinit var cameraExecutor: ExecutorService
var cameraProvider: ProcessCameraProvider? = null//相机信息
var preview: Preview? = null//预览对象
var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA//当前相机
var camera: Camera? = null//相机对象
private var imageCapture: ImageCapture? = null//拍照用例
var videoCapture: VideoCapture? = null//录像用例

开启相机预览

开启预览,把预览内容放进 PreviewView 里。

    private fun startCamera() {
        cameraExecutor = Executors.newSingleThreadExecutor()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            cameraProvider = cameraProviderFuture.get()//获取相机信息

            //预览配置
            preview = Preview.Builder()
                    .build()
                    .also {
                        it.setSurfaceProvider(viewFinder.createSurfaceProvider())
                    }

            imageCapture = ImageCapture.Builder().build()//拍照用例配置

            val imageAnalyzer = ImageAnalysis.Builder()
                    .build()
                    .also {
                        it.setAnalyzer(cameraExecutor, LuminosityAnalyzer { luma ->
                            Log.d(TAG, "Average luminosity: $luma")
                        })
                    }

            cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA//使用后置摄像头
            videoCapture = VideoCapture.Builder()//录像用例配置
//                .setTargetAspectRatio(AspectRatio.RATIO_16_9) //设置高宽比
//                .setTargetRotation(viewFinder.display.rotation)//设置旋转角度
//                .setAudioRecordSource(AudioSource.MIC)//设置音频源麦克风
                    .build()

            try {
                cameraProvider?.unbindAll()//先解绑所有用例
                camera = cameraProvider?.bindToLifecycle(this, cameraSelector, preview, imageCapture, videoCapture)//绑定用例
            } catch (exc: Exception) {
                Log.e(TAG, "Use case binding failed", exc)
            }

        }, ContextCompat.getMainExecutor(this))
    }

监听,写在Activity外面

typealias LumaListener = (luma: Double) -> Unit

再在Activity里面写一个内部类

private class LuminosityAnalyzer(private val listener: LumaListener) : ImageAnalysis.Analyzer {

        private fun ByteBuffer.toByteArray(): ByteArray {
            rewind()
            val data = ByteArray(remaining())
            get(data)
            return data
        }

        override fun analyze(image: ImageProxy) {

            val buffer = image.planes[0].buffer
            val data = buffer.toByteArray()
            val pixels = data.map { it.toInt() and 0xFF }
            val luma = pixels.average()

            listener(luma)

            image.close()
        }
    }

界面销毁时关闭线程

override fun onDestroy() {
    super.onDestroy()
    cameraExecutor.shutdown()
}

拍照方法

private fun takePhoto() {
    val imageCapture = imageCapture ?: return
    val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).path +
            "/CameraX" + SimpleDateFormat(FILENAME_FORMAT, Locale.CHINA).format(System.currentTimeMillis()) + ".jpg")
    val outputOptions = ImageCapture.OutputFileOptions.Builder(file).build()
    imageCapture.takePicture(outputOptions, ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageSavedCallback {
                override fun onError(exc: ImageCaptureException) {
                    Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
                }
                override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                    val savedUri = Uri.fromFile(file)
                    val msg = "Photo capture succeeded: $savedUri"
                    Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                    Log.d(TAG, msg)
                }
            })
}

录像方法

private fun takeVideo() {
    //视频保存路径
    val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).path + "/CameraX" + SimpleDateFormat(
            FILENAME_FORMAT, Locale.CHINA
    ).format(System.currentTimeMillis()) + ".mp4")
    //开始录像
    videoCapture?.startRecording(file, Executors.newSingleThreadExecutor(), object : OnVideoSavedCallback {
        override fun onVideoSaved(@NonNull file: File) {
            //保存视频成功回调,会在停止录制时被调用
            Toast.makeText(this@MainActivity, file.absolutePath, Toast.LENGTH_SHORT).show()
        }
        override fun onError(videoCaptureError: Int, message: String, cause: Throwable?) {
            //保存失败的回调,可能在开始或结束录制时被调用
            Log.e("""onError: $message")
        }
    })


    btnStartVideo.setOnClickListener {
        //结束录像
        videoCapture?.stopRecording()//停止录制
        preview?.clear()//清除预览
        btnStartVideo.text = "Start Video"
        btnStartVideo.setOnClickListener {
            btnStartVideo.text = "Stop Video"
            takeVideo()
        }
        Toast.makeText(this, file.path, Toast.LENGTH_SHORT).show()
        Log.d("path", file.path)
    }
}

文中代码完整Demo

Github CameraX-Demo https://github.com/DubheBroken/CameraX-Demo

参考文章:

Google CameraX 开发文档  
掘金-JetPack之使用CameraX完成拍照和拍视频  
Stackoverflow-Exception 'open failed: EACCES (Permission denied)' on Android


浏览 163
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报