I’m trying to implement video recording in my Android app using CameraX. The app displays the camera preview correctly, but when I try to start recording, I get the following
error:Sending VideoRecordEvent Finalize [error: ERROR_NO_VALID_DATA]
Dependencies in build.gradle:
implementation ("androidx.camera:camera-camera2:1.3.0-rc01")
implementation ("androidx.camera:camera-lifecycle:1.3.0-rc01")
implementation ("androidx.camera:camera-view:1.3.0-rc01")
implementation ("androidx.camera:camera-video:1.3.0-rc01")
My related function:
private fun initializeVideoCapture() {
val recorder = Recorder.Builder()
.setQualitySelector(QualitySelector.from(Quality.HIGHEST))
.build()
videoCapture = VideoCapture.withOutput(recorder)
}
@SuppressLint("MissingPermission")
private fun startRecording() {
val videoCapture = this.videoCapture ?: return
val videoFile = File(
outputDirectory,
"${System.currentTimeMillis()}.mp4"
)
val outputOptions = FileOutputOptions.Builder(videoFile).build()
recording = videoCapture.output
.prepareRecording(this, outputOptions)
.withAudioEnabled()
.start(ContextCompat.getMainExecutor(this)) { recordEvent ->
when (recordEvent) {
is VideoRecordEvent.Start -> {
Toast.makeText(this, "Recording started", Toast.LENGTH_SHORT).show()
}
is VideoRecordEvent.Finalize -> {
if (recordEvent.hasError()) {
Toast.makeText(this, "Recording error", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Recording succeeded", Toast.LENGTH_SHORT).show()
}
recording?.close()
recording = null
}
}
}
}
private fun stopRecording() {
recording?.stop()
recording = null
}
private fun allPermissionsGranted() = ActivityCompat.checkSelfPermission(
this, Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this, Manifest.permission.RECORD_AUDIO
) == PackageManager.PERMISSION_GRANTED
private fun createOutputDirectory(): 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
}
I have ensured that the necessary permissions (CAMERA, RECORD_AUDIO) are requested and granted. The app correctly initializes the camera and displays the preview, but fails when attempting to start video recording.
What could be causing the ERROR_NO_VALID_DATA error, and how can I resolve it to successfully record and save videos?