AudioRecorder

Records the microphone to an audio file — a voice message, a voice note — from the audio-recorder plugin. To turn speech into text use SpeechRecognizer (speech.md); recording video is not available (index.md).

  • record a voice message from the microphone
  • show the record button only where the device can record (AudioRecorder.supported)
  • show a live sound level meter while recording
  • stop the recording on its own after a time limit
  • pause and resume a recording
  • play back what was just recorded
  • upload the recording to the app's server
  • handle a refused microphone permission

Platforms: iOS and Android in the le.codes viewer app, the web and the web player; not on desktop or in headless tests, and not yet in an iOS or Android app built with lecodes app — check AudioRecorder.supported.

At a glance

TypeScript
const recorder = new AudioRecorder()
const status = UIText('Tap Record')
const meter = UIBox().style({ height: 6, width: 4, bgColor: '#e5484d', borderRadius: 3 })
recorder.addEventListener('level', v => meter.style({ width: 4 + v * 200 }))   // 0..1, ten times a second

const finish = async () => {
  const { file, duration } = await recorder.stop()     // the audio File, its length in seconds
  meter.style({ width: 4 })
  status.text = `Recorded ${duration.toFixed(1)} s`
  new AudioPlayer(file).play()                         // play it back
}
recorder.addEventListener('ended', () => { finish() })   // the one-minute limit was reached

const toggle = async () => {
  if (recorder.state !== 'inactive') return finish()
  await recorder.start({ maxDuration: 60_000 })        // asks for the microphone the first time
  status.text = 'Recording… tap to stop'
}

UIScreen(
  AudioRecorder.supported
    ? UIButton(UIText('Record')).onClick(() => { toggle().catch(e => { status.text = e.message }) })
    : UIText('Recording is not available on this device'),
  meter, status,
).style({ pt: 'safe-top', p: 20, gap: 12 }).open()

Add the recorder to the app: app.json plugins

AudioRecorder needs the audio-recorder plugin, listed in the app's app.json (one list for every platform; the le.codes viewer app has it whatever the list says):

JSON
{ "plugins": { "audio-recorder": "*" } }

AudioRecorder.supported is true where the host registered the plugin; read it before showing a record button (the At a glance does). Without it, start() rejects.

  • On the web the browser records (its MediaRecorder), and only on a secure page: an https page or localhost. On a plain http page, or in a browser without MediaRecorder, supported is false.
  • lecodes app does not know the plugin yet: syncing an iOS or Android app whose app.json lists it stops at Unknown plugin "audio-recorder". On a phone it runs in the le.codes viewer app.

Record a voice message: start and stop

start() begins recording from the microphone; stop() ends it and resolves with the recording — the audio File, its mimeType and its duration. One AudioRecorder makes one recording at a time and is reused: after stop() or cancel() it is ready for another start().

TypeScript
new AudioRecorder()                                     // nothing opens until start()
AudioRecorder.supported: boolean                      // this host has the plugin

recorder.start(options?: RecordOptions): Promise<void>  // asks for the microphone first
recorder.stop(): Promise<Recording>                     // the recording; also after `ended`
recorder.cancel(): void                                 // stop and throw the recording away
recorder.state: 'inactive' | 'recording' | 'paused' | 'stopped'

interface RecordOptions {
  bitrate?: number       // kilobits per second; default 64 (speech), 128 for music
  sampleRate?: number    // samples per second; default 44100 (on the web only a hint)
  maxDuration?: number   // milliseconds; then it stops on its own (`ended`). Default: no limit
}
interface Recording {
  file: File             // recording.m4a / .webm / .ogg
  mimeType: string       // 'audio/mp4', 'audio/webm', … — see "Which audio format"
  duration: number       // seconds of audio, the pauses left out
}
  • start() while a recording is under way (recording, paused or stopped) rejects — call stop() or cancel() first. cancel() with nothing under way does nothing.
  • state is 'stopped' after the recording ended on its own (ended); stop() still returns it.

Show a sound level meter while recording: the level event

The level event gives the microphone's input level, 0..1, about ten times a second while recording (not while paused) — for a meter or a waveform:

TypeScript
const recorder = new AudioRecorder()
const bar = UIBox().style({ height: 8, width: 2, bgColor: '#30a46c', borderRadius: 4 })
recorder.addEventListener('level', v => bar.style({ width: 2 + Math.min(1, v * 3) * 240 }))

const start = UIButton(UIText('Speak')).onClick(() => { recorder.start().catch(e => toast(e.message)) })
const stop = UIButton(UIText('Done')).onClick(() => { recorder.cancel(); bar.style({ width: 2 }) })

UIScreen(start, bar, stop).style({ pt: 'safe-top', p: 20, gap: 12 }).open()
Note

each platform measures the level its own way — iOS the average power, Android the peak, the web the RMS doubled — so the same voice reads higher on Android than on iOS. Scale it for a meter; don't use it as a threshold for "the user is speaking".

Limit the length of a voice message: maxDuration and the ended event

To limit a voice message to a minute, or 30 seconds, pass maxDuration (milliseconds) to start(): the recording stops on its own, ended fires with the reason, and the recording waits for stop(), which returns what was recorded until then:

TypeScript
const recorder = new AudioRecorder()
const status = UIText('')

recorder.addEventListener('ended', async reason => {
  // 'maxDuration' = the limit, 'interrupted' = a phone call (iOS) or the microphone taken away (web),
  // 'failed' = the encoder failed
  try {
    const { duration } = await recorder.stop()       // the file is kept until stop() or cancel()
    status.text = `Stopped (${reason}) after ${duration.toFixed(1)} s`
  } catch {
    status.text = 'Nothing was recorded'
  }
})

const record = UIButton(UIText('Record 30 s')).onClick(() => {
  recorder.start({ maxDuration: 30_000 }).then(() => { status.text = 'Recording…' }, e => { status.text = e.message })
})

UIScreen(record, status).style({ pt: 'safe-top', p: 20, gap: 12 }).open()
Note

on the web maxDuration counts from start(), the pauses included.

Pause and resume a recording

pause() holds the recording — the level stops and duration does not grow — and resume() continues it into the same file:

TypeScript
const recorder = new AudioRecorder()
const label = UIText('Pause')

const pauseOrResume = async () => {
  if (recorder.state === 'recording') { await recorder.pause(); label.text = 'Resume' }
  else if (recorder.state === 'paused') { await recorder.resume(); label.text = 'Pause' }
}

UIScreen(
  UIButton(UIText('Record')).onClick(() => { recorder.start().catch(e => toast(e.message)) }),
  UIButton(label).onClick(() => { pauseOrResume().catch(e => toast(e.message)) }),
).style({ pt: 'safe-top', p: 20, gap: 12 }).open()

pause() rejects unless the state is 'recording', resume() unless it is 'paused' (so both reject after ended). Android 6 has no pause: both reject 'failed' there.

Play back the recording: AudioPlayer

A recording's file is a source of AudioPlayer (media.md), which plays it from memory — no upload needed to listen to it:

TypeScript
const recorder = new AudioRecorder()
let last: File | null = null

const stop = async () => { last = (await recorder.stop()).file }

UIScreen(
  UIButton(UIText('Record')).onClick(() => { recorder.start().catch(e => toast(e.message)) }),
  UIButton(UIText('Stop')).onClick(() => { stop().catch(e => toast(e.message)) }),
  UIButton(UIText('Play')).onClick(() => { if (last) new AudioPlayer(last).play() }),
).style({ pt: 'safe-top', p: 20, gap: 12 }).open()

The phones' own recordings (AAC in .m4a) play everywhere; a .webm recorded in a browser does not play in the iOS player (Which audio format).

Upload the recording to the server

To upload a voice recording to the app's own server, pass the recording's File to a server function: a File parameter is an upload, and a t.file() field keeps it (Stored files):

TypeScript
// voice.server.ts — runs on the app's backend
const Voice = model({
  audio: t.file(),
  mimeType: t.string(),
  seconds: t.float(),
  createdAt: t.date().default("now"),
})
const db = defineDb({ Voice })

export async function sendVoice(audio: File, mimeType: string, seconds: number) {
  return db.voice.insert({ audio, mimeType, seconds })
}
TypeScript
// main.ts — the app
import { sendVoice } from "./voice.server"

const recorder = new AudioRecorder()
const status = UIText('')

const send = async () => {
  const { file, mimeType, duration } = await recorder.stop()
  await sendVoice(file, mimeType, duration)          // the bytes go with the call
  status.text = 'Sent'
}
recorder.addEventListener('ended', () => { send().catch(e => { status.text = e.message }) })   // the limit

const toggle = async () => {
  if (recorder.state !== 'inactive') return send()
  await recorder.start({ maxDuration: 60_000 })
  status.text = 'Recording… tap to send'
}

UIScreen(
  UIButton(UIText('Voice message')).onClick(() => { toggle().catch(e => { status.text = e.message }) }),
  status,
).style({ pt: 'safe-top', p: 20, gap: 12 }).open()

A stored file is at most 10 MB; a minute of speech at the default 64 kbit/s is about 480 KB. The row's audio.url is what another user's AudioPlayer plays. To post it to another HTTP API instead, put the File in a FormData (network.md).

Which audio format the recording is: mimeType

The format is the platform's encoder, and mimeType says which:

Where Format mimeType file.name
iOS, Android AAC in MPEG-4 'audio/mp4' recording.m4a
the web, the web player what the browser's MediaRecorder encodes: MPEG-4 where the browser can (Safari does), else Opus in WebM 'audio/mp4', 'audio/webm' (or 'audio/ogg') recording.m4a / .webm / .ogg

A chat whose messages must play on every device transcodes the web's WebM on its server, since the iOS player does not play WebM. Send mimeType along with the file (as above): the backend reads a stored file's type from its bytes, and an audio-only file may read as video/webm or video/mp4 there.

Microphone permission and errors

The first start() asks for the microphone: on iOS and Android the host's permission dialog, on the web the browser's. A refusal rejects with 'denied'; a rejection's code is e.message.

Call Rejects with When
start() 'denied' the user refused the microphone (iOS asks once: then only Settings turns it on)
start() 'failed' the recorder could not start: no input, the audio taken by a call
start() an Error the plugin is not on this host, or a recording is under way
pause() / resume() an Error · 'failed' not recording / not paused · Android 6
stop() 'failed' nothing could be encoded (a stop right after the start on Android)

To ask before the first recording, or to send the user to Settings after a refusal, use permissions (permissions.md):

TypeScript
const recorder = new AudioRecorder()
const status = UIText('')

const record = async () => {
  try {
    await recorder.start()
    status.text = 'Recording…'
  } catch (e) {
    if (e.message !== 'denied') { status.text = `Could not record: ${e.message}`; return }
    status.text = 'Allow the microphone in Settings to record'
    permissions.openSettings()                     // the app's page of the system settings (not on the web)
  }
}

UIScreen(UIButton(UIText('Record')).onClick(() => { record() }), status).style({ pt: 'safe-top', p: 20, gap: 12 }).open()

See also