Problem recording long-duration videos on Android using MediaRecorder with OpenCV

Hello everyone,

I am working on an Android surveillance application that uses OpenCV for face detection and MediaRecorder to record videos when a face is detected. My goal is to record a 15-second video when exactly one face is detected. However, the resulting videos are only 3KB and are not playable.

I have set up MediaRecorder to record from a video surface as shown in the following snippet of my code:

mediaRecorder = MediaRecorder().apply {
    setVideoSource(MediaRecorder.VideoSource.SURFACE)
    setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
    setVideoEncoder(MediaRecorder.VideoEncoder.H264)
    setVideoSize(face.width, face.height)
    setVideoFrameRate(30)
    setOutputFile(filePath)

    prepare()
    start()
}

The startRecording method is invoked when the face detection finds exactly one face, and the recording should stop after 15 seconds using a timer. Here is the relevant method:


private fun startTimerToStopRecording() {
    recordingThread = Executors.newSingleThreadScheduledExecutor().apply {
        schedule({
            stopRecording()
        }, 15, TimeUnit.SECONDS)
    }
}

The resulting video files are 3KB and contain no playable video data. I am not sure if the problem lies in how I set up the MediaRecorder or in how I handle the flow of face detection and video recording.
Question

Could someone help me identify what might be causing this problem with the video files? Is there any MediaRecorder configuration I might be missing or any additional considerations when working with OpenCV and MediaRecorder together?

I appreciate any guidance or code examples you could provide.

maybe show, how you write those (cropped ?) frames ?

The problem you describe happens with OpenCV’s own VideoWriter, but since you use Android APIs instead of that, IDK how to help.