Recording audio and video on Android into MediaStore
androidmediarecordercameraxmediastoreforeground-servicemicrophonescoped-storage
A recorder app has three jobs: capture without being killed, save where the user and other apps can find the result, and handle the camera's orientation. This comes from Justin's Studio app (io.jhampton.studio, Kotlin + Compose + CameraX, 2026-10-29). Verified on the emulator's virtual cameras; real-hardware behavior (stereo mics, 4K, long screen-off recordings) was still unchecked at the time of writing.
Saving into the shared MediaStore
- Put recordings in public collections so they show up in other apps and over USB: audio under
Music/<App>/, video underMovies/<App>/, by settingRELATIVE_PATH. No storage permission is needed on API 29+ to create files there. - Write into a pending entry. Insert with
IS_PENDING = 1(plusIS_RECORDING = 1on API 31+ for audio andIS_MUSIC = 0so it does not land in music players' libraries), open the URI's file descriptor for the recorder, and on success updateIS_PENDING = 0. Until then other apps cannot see a half-written file. On failure or discard, delete the entry. - List your own files with a query on
RELATIVE_PATH = ?andIS_PENDING = 0. - The scanner lags. Right after publishing,
DURATIONmay still be 0: write it yourself on publish, fall back toMediaMetadataRetrieverwhen listing, and refresh the list again a second or two later. - After a reinstall the app no longer owns its old files, so a plain delete fails with a security exception. Use
MediaStore.createDeleteRequest(API 30+) and launch the returned intent so the user confirms. Renaming works throughDISPLAY_NAMEfor owned files.
Audio with MediaRecorder
- Run it in a foreground service of type
microphone(FOREGROUND_SERVICE_MICROPHONE), started while the app is visible, so recording continues with the screen off. CallstartForegroundfirst thing inonStartCommand. Hold a partial wake lock (with a generous timeout) while recording. The notification can carry Pause/Resume and Stop actions, and updating it about once a second is enough for an elapsed-time readout. - Audio source matters more than codec:
CAMCORDERgets stereo on phones with a mic pair and the camcorder tuning.- For "raw" sound, check
AudioManager.getProperty(PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED) == "true"and useUNPROCESSED; otherwiseVOICE_RECOGNITIONis the least-processed common source (no noise suppression or automatic gain on most devices). - Formats: AAC in MPEG-4 (
.m4a) at 128 or 256 kbps, or Opus in Ogg (API 29+) for small files. MediaRecorder.getMaxAmplitude()polled every ~50 ms is enough for a level meter and scrolling waveform; convert to dBFS with20·log10(amp/32767)and draw a −60..0 dB scale so quiet speech still moves the bar. Set the sample rate (48 kHz), bit rate and channel count explicitly.stop()throws if nothing was recorded (stopped within a fraction of a second). Catch it, and delete the pending entry instead of publishing an empty file.- Track elapsed time as banked time plus the current run since
elapsedRealtime(), so pauses are excluded and the display survives recomposition.
Video with CameraX
Recorder+VideoCapture+Preview, bound to the lifecycle. Pick quality withQualitySelector.from(wanted, FallbackStrategy.lowerQualityOrHigherThan(Quality.SD))so 4K falls back on cameras that lack it. CheckRecorder.getVideoCapabilities(cameraInfo).isStabilizationSupportedbefore enabling stabilization.- Output with
MediaStoreOutputOptionsand the sameRELATIVE_PATHcontent values; CameraX handles the pending flag. - Check
hasCamerafor the selector and fall back to the other lens; emulators and some tablets have only one. - Portrait-locked UI, sideways video: if the activity never rotates, CameraX thinks the phone is always upright and sideways videos play sideways. Use an
OrientationEventListenerto setvideoCapture.targetRotation(45–135° →ROTATION_270, 135–225° →ROTATION_180, 225–315° →ROTATION_90, elseROTATION_0), and stop updating it once recording starts. - The microphone is exclusive: refuse to start video while the audio service is recording, with a message, rather than letting one fail silently.
Playback
Hide system bars and unlock rotation while a video plays full screen, and keep the sound on/off toggle visible at every screen size (hardware volume keys cannot clear a mute).