For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/angular-lynx/hardware/audio-recorder.md.

LynxAudioRecorder

Records audio from the microphone: a voice note, a voice message, or a meeting to transcribe. import { LynxAudioRecorder } from '@blotch/angular-lynx';

A recording follows how loud the person is as they speak. It stops into a clip: an .m4a file you can play back, share with LynxShare or upload.

Turn it on

Add permissions.microphone to the build target's options in angular.json, with the reason iOS shows when it asks:

angular.json
"options": {
  "permissions": { "microphone": "Records your voice notes" }
}

What it adds:

  • iOS: NSMicrophoneUsageDescription, the reason iOS's prompt shows.
  • Android: the RECORD_AUDIO permission, which Android asks the person for the first time the app records. The microphone feature is declared not required, so Google Play still offers the app to devices without one.

Without it, the native code is left out of both apps. permission is then unsupported, and start() rejects with unavailable.

See Turn on device features for every setting.

Usage

import { Component, inject, signal } from '@angular/core';
import {
  AudioRecorderError,
  type AudioRecording,
  LYNX_ELEMENTS,
  LynxAudioRecorder,
} from '@blotch/angular-lynx';

@Component({
  selector: 'app-voice-note',
  imports: [LYNX_ELEMENTS],
  template: `
    @if (recording(); as note) {
      <view class="meter" [style.width.%]="note.level() * 100"></view>
      @if (note.state() === 'paused') {
        <view (bindtap)="note.resume()"><text>Resume</text></view>
      }
      <view (bindtap)="send()"><text>Send</text></view>
      <view (bindtap)="discard()"><text>Discard</text></view>
    } @else {
      <view (bindtap)="record()"><text>Record</text></view>
    }
    <text>{{ status() }}</text>
  `,
})
export class VoiceNote {
  readonly #recorder = inject(LynxAudioRecorder);
  readonly recording = signal<AudioRecording | undefined>(undefined);
  readonly status = signal('');

  async record() {
    try {
      this.recording.set(await this.#recorder.start({ maxDuration: 120_000 }));
    } catch (error) {
      if (error instanceof AudioRecorderError && error.code === 'denied') {
        this.status.set('Allow the microphone in Settings to record');
        return;
      }
      this.status.set((error as Error).message);
    }
  }

  // Also after maxDuration stopped it: stop() resolves with that clip, and
  // again with the same clip when an upload is tried again.
  async send() {
    const note = this.recording()!;
    try {
      const clip = await note.stop();
      this.status.set(`Sending ${Math.round(clip.durationMs / 1000)} s`);
      // A Blob body is sent with the clip's type: audio/mp4 on a phone, and
      // whatever the browser records in the web preview (often audio/webm).
      // Lynx has no FormData.
      const response = await fetch(`https://example.com/notes/${clip.name}`, {
        method: 'PUT',
        body: await clip.blob(),
      });
      if (!response.ok) throw new Error(`The server said ${response.status}`);
      // Kept until it's sent, so Send can try again. Only this note: the
      // person may have discarded it and started another meanwhile.
      if (this.recording() === note) this.recording.set(undefined);
      this.status.set('Sent');
      // The server has it, so the phone needn't keep the file. If that
      // fails, the system clears it with the rest of the temporary folder.
      await clip.delete().catch(() => {});
    } catch (error) {
      this.status.set(`Not sent: ${(error as Error).message}`);
    }
  }

  async discard() {
    const note = this.recording()!;
    if (note.state() !== 'stopped') {
      // Still open: cancel() ends it and deletes what it recorded.
      await note.cancel();
    } else {
      // Stopped by maxDuration, or by a Send that failed: delete its clip.
      // A recording that failed has no clip, and nothing to delete.
      const clip = await note.stop().catch(() => undefined);
      try {
        await clip?.delete();
      } catch (error) {
        // Kept, so Discard can try again.
        this.status.set(`Not discarded: ${(error as Error).message}`);
        return;
      }
    }
    // Only this note: the person may have started another meanwhile.
    if (this.recording() === note) this.recording.set(undefined);
  }
}

The first start() asks the person for the microphone. Call requestPermission() first to ask at a moment of your choosing, such as after a screen that says what the microphone is for.

The note keeps its Send button once maxDuration stops it, and once the system pauses it. One recording is open at a time: a second start() rejects with busy until the first is stopped or canceled.

Pause, resume and the background

pause() and resume() carry on into the same clip, and the pause isn't counted in its length. The system pauses a recording too, and its state turns paused:

  • iOS: a phone call, FaceTime or Siri taking the microphone, or the app going to the background.
  • Android: the app going to the background.

A recording runs only while the app is in the foreground. Android gives an app in the background only silence, and iOS stops it without the background audio mode. Show a Resume button while it's paused.

Share or upload a clip

// Injected in a field: a method has no injection context after an await.
readonly #share = inject(LynxShare);

async shareNote(recording: AudioRecording) {
  const clip = await recording.stop();
  await this.#share.share({
    files: [{ blob: await clip.blob(), name: clip.name }],
  });
}

clip.uri is a file:// URL in the app's temporary folder, which the system may clear once the app isn't running. To keep it, save await clip.blob() with LynxFilePicker or upload it.

Delete a clip

clip.delete() deletes a stopped clip's file, such as once it's sent or the person discards it, rather than leaving it until the system clears the temporary folder. In the web preview it lets go of the clip's bytes and its blob: URL. After it, blob() rejects with failed. Calling it again does nothing, and neither does a file the system has already cleared.

cancel() ends a recording that's still open and deletes what it recorded, so it has no clip to delete.

Methods

MethodReturnsDescription
start(options?)Promise<AudioRecording>Starts recording, asking for the microphone first if it needs to
requestPermission()Promise<MicrophonePermission>Asks for the microphone, if the person hasn't been asked
permissionSignal<MicrophonePermission>granted, denied, undetermined (not asked yet) or unsupported

permission is read again each time the app comes back to the foreground, so it turns granted after the person allows the microphone in Settings. Android can't tell an app whether it asked before, so there it's undetermined until the app asks.

AudioRecordingOptions

OptionTypeDescription
maxDurationnumberThe longest the recording may be, in milliseconds, not counting pauses. It stops by itself at this, within a tenth of a second

AudioRecording

MemberTypeDescription
stateSignal<AudioRecordingState>recording, paused or stopped
levelSignal<number>How loud the microphone is, from 0 to 1, about ten times a second. 0 while paused
durationMsSignal<number>How long it is so far, in milliseconds, not counting pauses
errorSignal<AudioRecorderError | undefined>Why it ended by itself, such as the microphone failing
pause()Promise<void>Pauses it
resume()Promise<void>Carries on after a pause, into the same clip
stop()Promise<AudioClip>Ends it and resolves with the clip. After maxDuration ended it, resolves with that clip
cancel()Promise<void>Ends it and deletes what it recorded

level is the loudness from -60 dBFS (0) to full scale (1), the same on every platform, for a meter or a waveform.

AudioClip

FieldTypeDescription
uristringThe file: a file:// URL on a phone, a blob: URL in the web preview
namestringA file name for it, such as recording-1764380000000.m4a
durationMsnumberHow long it plays, in milliseconds
mimeTypestringaudio/mp4 (AAC) on a phone; the browser's own format in the web preview
sizenumberIts size, in bytes
blob()Promise<Blob>Its bytes, for LynxShare or a fetch() body
delete()Promise<void>Deletes its file. blob() rejects after it

A phone records AAC in mono at 44.1 kHz, asking the encoder for 64,000 bits a second.

AudioRecorderError

start(), stop() and clip.delete() reject with an AudioRecorderError, whose code is one of:

CodeWhen
unavailableThe host can't record: Lynx Explorer, or an app built without permissions.microphone
deniedThe person refused the microphone. Only Settings can change it now: openAppSettings() opens the app's page there
busyAnother recording is open, or another app or a call has the microphone
failedAnything else; the message has the platform's reason

Platform support

PlatformSupport
iOSAVAudioRecorder, AAC in .m4a. The Simulator records from the Mac's microphone
AndroidMediaRecorder, AAC in .m4a
Web previewThe browser's MediaRecorder: audio/mp4 where the browser records it, else audio/webm
Lynx Explorerunavailable

Testing

The testing library fakes the microphone. The first start() asks and the person allows it; setMicrophonePermission() says otherwise, and setRecordedAudio() sets what a clip holds:

setRecordedAudio({ bytes: new Uint8Array([1, 2, 3]), durationMs: 4200 });
await render(VoiceNote);
fireEvent.tap(screen.getByText('Record'));
await waitForUpdate();
emitAudioLevel(0.5);
fireEvent.tap(screen.getByText('Send'));
await waitForUpdate();
expect(screen.getByText('Sending 4 s')).toBeInTheDocument();