Get started
Introduction
Installation
Your first app
Tutorials
Fission tutorials
Record audio with the Android microphone capability
Core concepts
Components
State and effects
Protected routes
Server-side rendering
Styling
Testing
Deployment
Reference
API reference
Cookbook
Fission 0.16.0
Documentation version
Read the changelog →

Record audio with the Android microphone capability

Record a deliberate two-second inspection note, consume its one-shot stream asynchronously and preserve the previous recording if replacement fails.
Android

What you will build

Request and recheck microphone access, capture a short note and retain its actual bytes in session memory without claiming they were saved or uploaded.
Check microphone access before enabling a deliberate recording action
Decode permission and capture results through the capability input
Read the one-shot stream in a job with an explicit memory bound
Keep raw PCM, encoded audio, retained bytes and saved files distinct
An inspection note can contain sound that is difficult to describe in text. That does not mean the app should start recording when the screen opens, or report a recording as attached merely because the host returned a stream handle.
This app starts with an equipment reference and written observation. The user checks access, requests permission if needed, and deliberately records a two-second note. A job consumes the one-shot audio stream with a 256 KiB limit. Only then does the new recording replace the previous one in session memory. There is no upload, persistent save or playback claim.
Start from a new project (optional)

Create the Android project

Complete SDK/NDK setup and prepare an emulator or a phone.
cargo install cargo-fission
fission init android-record-audio-with-the-android-microphone-capability
cd android-record-audio-with-the-android-microphone-capability
fission add-target android --project-dir .
fission add-capability microphone --project-dir .
cargo add serde_yaml
Keep the generated main entrypoint. The microphone, stream reader, state and screen have separate responsibilities, but native and Web run those same modules.

Run the finished example

fission run --target android --project-dir .

1. Keep permission, capture and byte delivery distinct

The Android provider returns a permission snapshot immediately after requesting its OS prompt. Finish the prompt before checking again; a callback is not proof the user has already answered it. The recording button remains unavailable until access and an input device have been confirmed.
Pending covers capture and byte consumption. Otherwise a second capture could overtake the first stream read and replace the wrong recording. Written notes remain editable, and a failed replacement leaves the previous bytes intact. The equipment reference stays read-only whilst audio is retained so it cannot silently relabel an existing recording; discard the recording before changing equipment.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/state.rs","value":"src-state-rs"},{"index":1,"label":"src/jobs.rs","value":"src-jobs-rs"},{"index":2,"label":"src/app.rs","value":"src-app-rs"},{"index":3,"label":"src/translations.rs","value":"src-translations-rs"},{"index":4,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":5,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"},{"index":6,"label":"src/lib.rs","value":"src-lib-rs"},{"index":7,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/state.rs","value":"src-state-rs"}
use fission::prelude::*;
use crate::jobs::{ReadRecording, READ_RECORDING};

#[derive(Debug, Default)]
pub struct VoiceNoteState {
    pub availability: Option<MicrophoneAvailability>,
    pub pending: bool,
    pub note: Option<(MicrophoneCapture, Vec<u8>)>,
    pub incoming: Option<MicrophoneCapture>,
    pub issue: Option<&'static str>,
}
impl GlobalState for VoiceNoteState {}
impl VoiceNoteState {
    pub fn can_record(&self) -> bool {
        !self.pending && self.availability.as_ref().is_some_and(|value| {
            value.permission == MicrophonePermission::Granted && !value.devices.is_empty()
        })
    }
}

pub fn check_microphone(state: &mut VoiceNoteState, ctx: &mut ReducerContext<VoiceNoteState>) {
    if state.pending { return; }
    state.pending = true;
    state.issue = None;
    let ok = ctx.effects.bind(MicrophoneChecked, reduce_with!(microphone_checked));
    let err = ctx.effects.bind(MicrophoneCheckFailed, reduce_with!(microphone_check_failed));
    ctx.effects.microphone().availability().on_ok(ok).on_err(err);
}
#[fission_reducer(MicrophoneChecked)]
pub fn microphone_checked(state: &mut VoiceNoteState, ctx: &mut ReducerContext<VoiceNoteState>) {
    state.pending = false;
    match ctx.input.capability_ok(GET_MICROPHONE_AVAILABILITY) {
        Some(value) => state.availability = Some(value),
        None => state.issue = Some("voice.missing"),
    }
}
#[fission_reducer(MicrophoneCheckFailed)]
pub fn microphone_check_failed(state: &mut VoiceNoteState, ctx: &mut ReducerContext<VoiceNoteState>) {
    state.pending = false;
    state.availability = None;
    state.issue = Some(match ctx.input.capability_error(GET_MICROPHONE_AVAILABILITY) {
        Some(error) if error.code == "unsupported" => "voice.unsupported",
        _ => "voice.failed",
    });
}

#[fission_reducer(RequestMicrophoneAccess)]
pub fn request_microphone_access(
    state: &mut VoiceNoteState, reason: String, ctx: &mut ReducerContext<VoiceNoteState>,
) {
    if state.pending { return; }
    state.pending = true;
    state.issue = None;
    let ok = ctx.effects.bind(MicrophoneAccessReceived, reduce_with!(microphone_access_received));
    let err = ctx.effects.bind(MicrophoneAccessFailed, reduce_with!(microphone_access_failed));
    ctx.effects.microphone().request_permission(MicrophonePermissionRequest {
        reason: Some(reason),
    }).on_ok(ok).on_err(err);
}
#[fission_reducer(MicrophoneAccessReceived)]
pub fn microphone_access_received(state: &mut VoiceNoteState, ctx: &mut ReducerContext<VoiceNoteState>) {
    state.pending = false;
    state.availability = None;
    state.issue = Some(if ctx.input.capability_ok(REQUEST_MICROPHONE_PERMISSION).is_some() {
        "voice.recheck"
    } else { "voice.missing" });
}
#[fission_reducer(MicrophoneAccessFailed)]
pub fn microphone_access_failed(state: &mut VoiceNoteState, ctx: &mut ReducerContext<VoiceNoteState>) {
    state.pending = false;
    state.issue = Some(match ctx.input.capability_error(REQUEST_MICROPHONE_PERMISSION) {
        Some(error) if error.code == "unsupported" => "voice.unsupported",
        _ => "voice.failed",
    });
}

pub fn record_voice_note(state: &mut VoiceNoteState, ctx: &mut ReducerContext<VoiceNoteState>) {
    if !state.can_record() { return; }
    state.pending = true;
    state.issue = None;
    let ok = ctx.effects.bind(VoiceCaptured, reduce_with!(voice_captured));
    let err = ctx.effects.bind(VoiceCaptureFailed, reduce_with!(voice_capture_failed));
    ctx.effects.microphone().capture_audio(MicrophoneCaptureRequest {
        device_id: None, duration_ms: 2_000, sample_rate_hz: Some(16_000),
        channels: Some(1), sample_format: AudioSampleFormat::I16,
    }).on_ok(ok).on_err(err);
}
#[fission_reducer(VoiceCaptured)]
pub fn voice_captured(state: &mut VoiceNoteState, ctx: &mut ReducerContext<VoiceNoteState>) {
    let Some(capture) = ctx.input.capability_ok(CAPTURE_MICROPHONE_AUDIO) else {
        state.pending = false;
        state.issue = Some("voice.missing");
        return;
    };
    let request = ReadRecording { stream: capture.stream };
    state.incoming = Some(capture);
    let ok = ctx.effects.bind(VoiceBytesRead, reduce_with!(voice_bytes_read));
    let err = ctx.effects.bind(VoiceBytesFailed, reduce_with!(voice_bytes_failed));
    ctx.effects.app(READ_RECORDING, request).on_ok(ok).on_err(err);
}
#[fission_reducer(VoiceCaptureFailed)]
pub fn voice_capture_failed(state: &mut VoiceNoteState, ctx: &mut ReducerContext<VoiceNoteState>) {
    state.pending = false;
    state.issue = Some(match ctx.input.capability_error(CAPTURE_MICROPHONE_AUDIO) {
        Some(error) if error.code == "permission_denied" => {
            state.availability = None;
            "voice.denied"
        }
        Some(error) if error.code == "unsupported" => "voice.unsupported",
        _ => "voice.failed",
    });
}
#[fission_reducer(VoiceBytesRead)]
pub fn voice_bytes_read(state: &mut VoiceNoteState, ctx: &mut ReducerContext<VoiceNoteState>) {
    state.pending = false;
    match (state.incoming.take(), ctx.input.job_ok(READ_RECORDING)) {
        (Some(metadata), Some(bytes)) => state.note = Some((metadata, bytes)),
        _ => state.issue = Some("voice.missing"),
    }
}
#[fission_reducer(VoiceBytesFailed)]
pub fn voice_bytes_failed(state: &mut VoiceNoteState, ctx: &mut ReducerContext<VoiceNoteState>) {
    state.pending = false;
    state.incoming = None;
    let _ = ctx.input.job_err(READ_RECORDING);
    state.issue = Some("voice.read_failed");
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn permission_and_a_device_are_required() {
        let mut state = VoiceNoteState::default();
        state.availability = Some(MicrophoneAvailability {
            permission: MicrophonePermission::Granted, devices: vec![],
        });
        assert!(!state.can_record());
        state.availability.as_mut().unwrap().devices.push(MicrophoneDevice {
            id: "test-input".into(), label: None, is_default: true,
        });
        assert!(state.can_record());
        state.pending = true;
        assert!(!state.can_record());
    }
}
{"id":"fission-tabs-1","index":1,"label":"src/jobs.rs","value":"src-jobs-rs"}
use fission::core::{DataStreamId, JobCtx, JobRef, JobSpec};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ReadRecording { pub stream: DataStreamId }
#[derive(Debug)]
pub struct ReadRecordingJob;
impl JobSpec for ReadRecordingJob {
    type Request = ReadRecording;
    type Ok = Vec<u8>;
    type Err = String;
    const NAME: &'static str = "voice-note.read-recording";
}
pub const READ_RECORDING: JobRef<ReadRecordingJob> = JobRef::new(ReadRecordingJob::NAME);

pub async fn read_recording(request: ReadRecording, ctx: JobCtx) -> Result<Vec<u8>, String> {
    let mut stream = ctx.open_data_stream(request.stream).map_err(|error| error.to_string())?;
    let mut bytes = Vec::new();
    while let Some(chunk) = std::future::poll_fn(|cx| stream.as_mut().poll_next(cx)).await {
        let chunk = chunk.map_err(|error| error.to_string())?;
        if chunk.len() > (256_usize * 1024).saturating_sub(bytes.len()) {
            return Err("Recording exceeds the 256 KiB session limit".into());
        }
        bytes.extend_from_slice(&chunk);
    }
    if bytes.is_empty() { return Err("No audio bytes were returned".into()); }
    Ok(bytes)
}
{"id":"fission-tabs-1","index":2,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::state::*;

fission_component! {
    pub VoiceNoteScreen<VoiceNoteState> {
        state { subject: String = String::new(), written_note: String = String::new() }
    }
    view(screen, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let request = with_reducer!(
            cx.build, RequestMicrophoneAccess(cx.tr("voice.reason")), request_microphone_access
        );
    } =>
    SafeArea(child: Scroll(child: Container(
        Column(gap: tokens.spacing.m, children: [
            Text(cx.tr("voice.title")).size(tokens.typography.heading2_size),
            Text(cx.tr("voice.scope")),
            TextInput(
                label: Some(cx.tr("voice.subject").into()), bind: screen.subject,
                read_only: state.pending || state.note.is_some(), semantics_identifier: "voice.subject".to_owned(),
            ),
            TextInput(
                label: Some(cx.tr("voice.written").into()), bind: screen.written_note,
                multiline: true, semantics_identifier: "voice.written".to_owned(),
            ),
            Button(
                child: Text(cx.tr("voice.check")), key: "voice.check",
                disabled: state.pending, on_press: reduce { check_microphone(state, cx); },
            ),
            Button(
                child: Text(cx.tr("voice.request")), key: "voice.request",
                disabled: state.pending, on_press: request,
            ),
            if let Some(availability) = &state.availability {
                Text(cx.tr(if availability.permission == MicrophonePermission::Granted {
                    "voice.granted"
                } else { "voice.not_granted" }))
            },
            Button(
                child: Text(cx.tr("voice.record")), key: "voice.record",
                disabled: !state.can_record() || screen.subject.trim().is_empty(),
                on_press: reduce { record_voice_note(state, cx); },
            ),
            if state.pending {
                Spinner(motion: Some(SpinnerMotion::Default), label: cx.tr("voice.pending"))
            },
            if let Some(issue) = state.issue { Text(cx.tr(issue)).color(tokens.colors.error) },
            if let Some((metadata, bytes)) = &state.note {
                Column(gap: tokens.spacing.s, children: [
                    Text(cx.tr("voice.retained")),
                    Text(format!("{} {}", cx.tr("voice.bytes"), bytes.len())),
                    Text(format!("{} {}", cx.tr("voice.format"), metadata.content_type)),
                    Button(
                        child: Text(cx.tr("voice.discard")), key: "voice.discard",
                        disabled: state.pending,
                        on_press: reduce { state.note = None; },
                    ),
                ])
            },
        ])
    ).padding_all(tokens.spacing.l)))
}
{"id":"fission-tabs-1","index":3,"label":"src/translations.rs","value":"src-translations-rs"}
use std::collections::HashMap;
use fission::prelude::*;

pub fn create_env() -> Env {
    let mut env = Env::default();
    env.locale = Locale::from("en-US");
    for (locale, source) in [
        ("en-US", include_str!("../i18n/en-US.yaml")),
        ("es-ES", include_str!("../i18n/es-ES.yaml")),
    ] {
        let messages: HashMap<String, String> =
            serde_yaml::from_str(source).expect("valid checked-in translations");
        env.i18n.add_bundle(TranslationBundle { locale: Locale::from(locale), messages });
    }
    env
}
{"id":"fission-tabs-1","index":4,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
voice.title: "Record a short inspection note"
voice.scope: "Enter the equipment reference first. Audio stays in this session; nothing is uploaded. Ask anyone nearby before recording."
voice.subject: "Equipment reference"
voice.written: "Written observation"
voice.check: "Check microphone and permission"
voice.request: "Request microphone access"
voice.reason: "Record a two-second inspection note."
voice.record: "Record or replace 2-second note"
voice.granted: "Microphone access is granted. Check that the device is available before recording."
voice.not_granted: "Microphone access is not granted. The written observation remains available."
voice.pending: "Waiting for permission, recording or reading audio…"
voice.retained: "Audio bytes retained for this session; not saved or sent."
voice.bytes: "Bytes:"
voice.format: "Returned format:"
voice.discard: "Discard recording"
voice.missing: "The provider returned no usable result. The previous recording is unchanged."
voice.recheck: "Finish the Android prompt, then check the microphone again."
voice.denied: "Access was denied. The previous recording and written observation are unchanged."
voice.unsupported: "This host does not support this microphone operation."
voice.failed: "The microphone operation failed. Check access and try again."
voice.read_failed: "The recording could not be read within the session limit. The previous recording is unchanged."
{"id":"fission-tabs-1","index":5,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
voice.title: "Grabar una nota breve de inspección"
voice.scope: "Introduce primero la referencia del equipo. El audio solo se conserva en esta sesión; no se carga. Pide permiso a las personas cercanas."
voice.subject: "Referencia del equipo"
voice.written: "Observación escrita"
voice.check: "Comprobar micrófono y permiso"
voice.request: "Solicitar acceso al micrófono"
voice.reason: "Grabar una nota de inspección de dos segundos."
voice.record: "Grabar o sustituir nota de 2 segundos"
voice.granted: "El acceso está concedido. Comprueba que el dispositivo esté disponible antes de grabar."
voice.not_granted: "No hay acceso al micrófono. Puedes escribir la observación."
voice.pending: "Esperando permiso, grabación o lectura del audio…"
voice.retained: "Audio conservado en esta sesión; no se ha guardado ni enviado."
voice.bytes: "Bytes:"
voice.format: "Formato devuelto:"
voice.discard: "Descartar grabación"
voice.missing: "El proveedor no devolvió un resultado útil. Se conserva la grabación anterior."
voice.recheck: "Termina el diálogo de Android y comprueba de nuevo el micrófono."
voice.denied: "Se denegó el acceso. Se conservan la grabación y la observación anteriores."
voice.unsupported: "Este entorno no admite esta operación de micrófono."
voice.failed: "La operación falló. Comprueba el acceso y vuelve a intentarlo."
voice.read_failed: "No se pudo leer el audio dentro del límite de sesión. Se conserva la grabación anterior."
{"id":"fission-tabs-1","index":6,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
pub mod state;
pub mod jobs;
mod translations;

use app::VoiceNoteScreen;
use state::VoiceNoteState;
use fission::prelude::*;

#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<VoiceNoteState, _>::new(VoiceNoteScreen::new())
        .with_env(translations::create_env())
        .with_async(|asyncs| {
            asyncs.register_job(jobs::READ_RECORDING, |request, ctx| async move {
                jobs::read_recording(request, ctx).await
            });
        })
        .run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<VoiceNoteState, VoiceNoteScreen> {
    let app = MobileApp::<VoiceNoteState, _>::new(VoiceNoteScreen::new())
        .with_env(translations::create_env())
        .with_async(|asyncs| {
            asyncs.register_job(jobs::READ_RECORDING, |request, ctx| async move {
                jobs::read_recording(request, ctx).await
            });
        });
    #[cfg(all(target_os = "android", debug_assertions))]
    let app = app.with_test_control_port(48761);
    app
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> { mobile_app().run() }

#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
    let _ = mobile_app().run_with_android_app(app_handle);
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<VoiceNoteState, _>::new(VoiceNoteScreen::new())
        .with_env(translations::create_env())
        .with_async(|asyncs| {
            asyncs.register_job(jobs::READ_RECORDING, |request, ctx| async move {
                jobs::read_recording(request, ctx).await
            });
        })
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":7,"label":"preview/lib.rs","value":"preview-lib-rs"}
include!("../src/lib.rs");
{"id":"fission-tabs-1"}
The count is the number of bytes actually read, not a fabricated audio length. Discard releases the app's retained buffer. The default browser host uses real microphone access where supported; no memory provider records on the user's behalf.
Show the app preview
Hide the app preview

2. Verify the recording boundary on Android

cargo test
fission doctor android --project-dir .
adb devices -l
fission run --target android --device <adb-serial> --project-dir .
fission test --target android --project-dir .
fission build --target android --project-dir . --release
Test denial, a later grant, system microphone privacy controls and a recording on a physical phone. Check that the OS recording indicator agrees with the deliberate request and that a failed replacement preserves the previous recording. Do not log audio bytes or use a shared room recording as a test fixture without consent.
The current Android provider captures PCM, not a WAV file. Its returned content type identifies the sample format; the byte stream has no WAV container header. Browser providers can return a different encoded format. Consequently, renaming every result to .wav would be wrong: an export or playback feature must use the actual returned format and metadata.
The Android host clamps capture duration and configuration, and its duration field reflects the requested/clamped interval rather than an independently measured recording guarantee. It also currently implements cancellation as a no-op. This example therefore offers a short bounded capture, not a Stop button that promises immediate cancellation. Capture failure or delay is not a successful recording.
The unit test checks the app's availability gate. Host startup, microphone permission, actual recorded content and release packaging are different checks; none can be inferred from that test or from the preview.

Current references

A qualified phone run records the permission outcome, returned format and usable captured content without publishing private audio. Persisting, playing or transmitting that content requires its own explicit product action and data policy.