Jagar
Jagar

Reputation: 872

How to capture a video with CameraX without saving the output to the Gallery?

I am following the official documentation to capture a video with CameraX, and I want to avoid saving the captured video in the gallery.
For now I am working on this part of the documentation code:

// Create MediaStoreOutputOptions for our recorder
val name = "CameraX-recording-" +
        SimpleDateFormat(FILENAME_FORMAT, Locale.US)
                .format(System.currentTimeMillis()) + ".mp4"
val contentValues = ContentValues().apply {
   put(MediaStore.Video.Media.DISPLAY_NAME, name)
}
val mediaStoreOutput = MediaStoreOutputOptions.Builder(this.contentResolver,
                              MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
                              .setContentValues(contentValues)
                              .build()

// 2. Configure Recorder and Start recording to the mediaStoreOutput.
val recording = videoCapture.output
                .prepareRecording(context, mediaStoreOutput)
                .withAudioEnabled()
                .start(ContextCompat.getMainExecutor(this), captureListener)

I noticed that prepaeRecording() can take FileOutputOptions instead of MediaStoreOutput, so I thought it could be where should I work but I have not found any example with FileOutputOptions and CameraX, and also I want it to work with the scoped permissions.
Is that possible? and can you help with an example to avoid saving the video to the gallery?

Upvotes: 6

Views: 3065

Answers (1)

Jagar
Jagar

Reputation: 872

I was able to achieve it like below (tested on Android 11 SDK 30):

val folder = File(getExternalFilesDir(Environment.DIRECTORY_DCIM).toString() + File.separator + "MyApp")
if (!folder.exists()) {
   folder.mkdir()
}
val nomediaFile = File(folder.absolutePath + File.separator + ".nomedia")
if (!nomediaFile.exists()) {
    nomediaFile.createNewFile()
}
val outputFile = File.createTempFile("SOME_NAME", ".mp4", folder)
val fileOutputOptions = FileOutputOptions.Builder(outputFile).build()

Upvotes: 5

Related Questions