添加依赖
def camerax_version = "1.1.0-beta03"
// CameraX core library
implementation "androidx.camera:camera-core:$camerax_version"
// CameraX Camera2 extensions[可选]拓展库可实现人像、HDR、夜间和美颜、滤镜但依赖于OEM
implementation "androidx.camera:camera-camera2:$camerax_version"
// CameraX Lifecycle library[可选]避免手动在生命周期释放和销毁数据
implementation "androidx.camera:camera-lifecycle:$camerax_version"
// CameraX View class[可选]最佳实践,最好用里面的PreviewView,它会自行判断用SurfaceView还是TextureView来实现
implementation 'androidx.camera:camera-view:1.1.0-beta03'
在build.gradle
中添加CameraX依赖,最新版本可以从官网链接查看
声明权限
<uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在AndroidManifest.xml
中声明需要使用的权限
添加PreviewView布局
<androidx.camera.view.PreviewView
android:id="@+id/preview"
android:layout_height="match_parent"
android:layout_width="match_parent" />
PreviewView
可以根据不同场景,自行区分使用SurfaceView或者TextureView
自定义配置Camera
class CameraApplication : Application(), CameraXConfig.Provider {
override fun getCameraXConfig(): CameraXConfig {
return CameraXConfig.Builder.fromConfig(Camera2Config.defaultConfig())
.setMinimumLoggingLevel(Log.ERROR).build()
}
}
CameraXConfig
用于自定义相机的初始配置
检查Camera可用性
private fun openCamera() {
var cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
cameraProviderFuture.addListener({
cameraProvider = cameraProviderFuture.get()
bindPreview(cameraProvider)
}, ContextCompat.getMainExecutor(requireContext()))
}
选择相机、绑定生命周期并添加usecase
private fun bindPreview(cameraProvider: ProcessCameraProvider) {
cameraSelector = CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK).build()
preview = Preview.Builder()
.setTargetAspectRatio(AspectRatio.RATIO_16_9) //设置宽高比
.setTargetRotation(Surface.ROTATION_0)
.build()
preview.setSurfaceProvider(previewView.surfaceProvider)
imageCapture = ImageCapture.Builder()
.setTargetRotation(requireView().display.rotation)
.build()
val recorder = Recorder.Builder().build()
videoCapture = VideoCapture.withOutput(recorder)
try {
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(viewLifecycleOwner, cameraSelector, videoCapture, imageCapture, preview)
} catch (e: Exception) {
Log.e(TAG, "bind preview error: $e")
}
}
查看bindToLifecycle
方法可以看到,CameraX定义了一个UseCase的概念,以满足不同场景下Camera的使用,如代码中的preview
、imageCapture
、videoCapture
分别用于展示预览、拍摄照片、录制视频,同时也可以写成以下形式:
val useCaseGroup = UseCaseGroup.Builder()
.addUseCase(preview)
.addUseCase(imageCapture)
.addUseCase(videoCapture)
.build()
try {
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(viewLifecycleOwner, cameraSelector, useCaseGroup)
} catch (e: Exception) {
Log.e(TAG, "bind preview error: $e")
}
拍摄照片
private fun takePicture() {
var path = requireContext().cacheDir.canonicalPath + getFileName("jpeg")
val outputFileOptions = ImageCapture.OutputFileOptions.Builder(File(path)).build()
imageCapture.takePicture(outputFileOptions, ContextCompat.getMainExecutor(requireContext()),
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
Toast.makeText(requireContext(), "picture saved: $path", Toast.LENGTH_LONG).show()
}
override fun onError(exception: ImageCaptureException) {
Toast.makeText(requireContext(), "task picture error: $exception", Toast.LENGTH_LONG).show()
}
}
)
}
- 指定照片存储位置,照片默认为
JPEG
格式 - 使用
imageCapture.takePicture
拍照并监听回调
录制视频
private fun startRecording() {
var fileName = getFileName("mp4")
val contentValues = ContentValues().apply {
put(MediaStore.Video.Media.DISPLAY_NAME, fileName)
}
var mediaStoreOutput = MediaStoreOutputOptions.Builder(
requireActivity().contentResolver,
MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
.setContentValues(contentValues)
.build()
currentRecording = videoCapture.output
.prepareRecording(requireActivity(), mediaStoreOutput)
.start(mainThreadExecutor, captureListener)
}
private fun getFileName(type: String): String {
var date = Date()
var simpleDateFormat = SimpleDateFormat(FILENAME_FORMAT)
return simpleDateFormat.format(date) + ".$type"
}
private val captureListener = Consumer<VideoRecordEvent> { event ->
// TODO 视频状态监听处理
}
- 定义视频存储位置
- 调用
videoCapture.output
的prepareRecording
和start
方法开始录制视频(对应MediaRecorder中的两个方法) - 设置视频状态监听
captureListener