AudioRecorder
The microphone, from the audio-recorder plugin: records it to an audio file — a voice message, a
voice note, a take of a song — and says what it hears meanwhile: the volume (level) and the note
(pitch), for a tuner or a singing game. 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 or a waveform while recording
- build a tuner: the note that is played, how many cents off it is
- build a singing or humming game: the note the player sings, in real time
- listen to the microphone without recording a file
- 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
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`
if (file) 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):
{ "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's microphone is used, and only on a secure page: an
httpspage orlocalhost. On a plainhttppagesupportedisfalse. lecodes appdoes not know the plugin yet: syncing an iOS or Android app whoseapp.jsonlists it stops atUnknown 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().
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 {
file?: boolean // write the audio file; default true. false = only the events
raw?: boolean // the microphone without the system's voice processing; default false
rate?: number // how many times a second `level` and `pitch` fire; default 10, at most 50
bitrate?: number // kilobits per second; default 64 (speech), 128 for music
sampleRate?: number // samples per second; default 44100 (on the web and iOS only a hint)
maxDuration?: number // milliseconds; then it stops on its own (`ended`). Default: no limit
}
interface Recording {
file: File | null // recording.m4a / .webm / .ogg; null when started with `file: false`
mimeType: string // 'audio/mp4', 'audio/webm', … — see "Which audio format"; '' without a file
duration: number // seconds of audio, the pauses left out
}start()while a recording is under way (recording, paused or stopped) rejects — callstop()orcancel()first.cancel()with nothing under way does nothing.stateis'stopped'after the recording ended on its own (ended);stop()still returns it.fileisnullonly when the recording was started withfile: false(Listen without recording).
Show a sound level meter or a waveform: the level event
The level event gives the volume, 0..1: the loudest moment since the previous event, ten times
a second while recording (not while paused; rate changes how
often). It means the same on every platform.
const recorder = new AudioRecorder()
const bar = UIBox().style({ height: 8, width: 2, bgColor: '#30a46c', borderRadius: 4 })
// decibels: −60 dB..0 dB across the bar
const meterOf = (level: number) => Math.max(0, 1 + 20 * Math.log10(Math.max(level, 1e-6)) / 60)
recorder.addEventListener('level', v => bar.style({ width: 2 + meterOf(v) * 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()levelis the plain amplitude, and how high it reads depends on the device's microphone: a quiet instrument on a phone'srawmicrophone reads around 0.01–0.05, a quiet room around 0.005. Draw a meter in decibels (as above), not straight from the value; don't use a fixed threshold for "the user is speaking".- For the waveform of a voice message, collect the values while recording and send them with the file — a later screen draws the bars without the audio:
const recorder = new AudioRecorder()
const levels: number[] = []
recorder.addEventListener('level', v => levels.push(v)) // ten a second: 600 for a minute
const send = async () => {
const { file, duration } = await recorder.stop()
console.log(`${duration.toFixed(1)} s, ${levels.length} bars`, file?.name) // store `levels` with the message
}
UIScreen(
UIButton(UIText('Record')).onClick(() => { levels.length = 0; recorder.start().catch(e => toast(e.message)) }),
UIButton(UIText('Send')).onClick(() => { send().catch(e => toast(e.message)) }),
).style({ pt: 'safe-top', p: 20, gap: 12 }).open()Build a tuner: the pitch event
The pitch event says which note is heard: its frequency in Hz and how sure the detector is
(clarity, 0..1). It fires on the same tick as level. AudioRecorder.note() turns the
frequency into a note name and the cents it is off by.
const recorder = new AudioRecorder()
const name = UIText('–').style({ fontSize: 96, fontWeight: 700 })
const detail = UIText('Play a note')
// the median of the last half second: a steady reading from a quiet or decaying string
let recent: { at: number, frequency: number }[] = []
recorder.addEventListener('pitch', p => {
const now = Date.now()
if (p.frequency > 0) recent.push({ at: now, frequency: p.frequency })
recent = recent.filter(r => now - r.at <= 500)
if (recent.length === 0) { name.style({ opacity: 0.3 }); return } // no note: keep the last one, dimmed
const sorted = recent.map(r => r.frequency).sort((a, b) => a - b)
const frequency = sorted[sorted.length >> 1]
const note = AudioRecorder.note(frequency)!
name.style({ opacity: 1 })
name.text = note.name + note.octave
detail.text = `${frequency.toFixed(1)} Hz · ${note.cents >= 0 ? '+' : ''}${note.cents} cents`
})
const start = () => recorder.start({ file: false, raw: true, rate: 20 }) // no file, the raw microphone
UIScreen(
name, detail,
UIButton(UIText('Start')).onClick(() => { start().catch(e => { detail.text = e.message }) }),
UIButton(UIText('Stop')).onClick(() => { recorder.cancel() }),
).style({ pt: 'safe-top', p: 20, gap: 12, alignItems: 'center' }).open()recorder.addEventListener('pitch', (pitch: AudioPitch) => void)
type AudioPitch = {
frequency: number // Hz; 0 when there is no clear note (silence, noise)
clarity: number // 0..1: how sure the detector is of the note
}- The note is looked for only while
pitchhas a listener: a voice message without one costs nothing. A listener added or removed during a recording turns it on and off. - One note at a time, from 60 Hz to 1500 Hz: a voice, a guitar, most instruments. Chords are not recognized, and a bass guitar's lowest strings (41–55 Hz) are below the range.
- Use
raw: truefor a tuner and for singing (below): the system's voice processing takes a held note for noise and turns it down. - A quiet source — an unplugged electric guitar, a hum from across the room — is found in only some of the events, and a single reading may be tens of cents off. Show the median of the last half second, as above, not each event.
frequencyis0for "no note"; a reading with a note has aclarityof 0.85 or more. An app that wants only confident notes comparesclarityitself.
Turn a frequency into a note: AudioRecorder.note and midiNote
AudioRecorder.note(frequency) names the note nearest to a frequency;
AudioRecorder.midiNote(midi) makes a note of its MIDI number — a target to show, or to play as a
reference tone. Both work on every host, with or without the plugin.
AudioRecorder.note(frequency: number, a4 = 440): AudioNote | null // null for no frequency (0)
AudioRecorder.midiNote(midi: number, a4 = 440): AudioNote
type AudioNote = {
name: string // 'C', 'C#', 'D', … 'B' (sharps, no flats)
octave: number // A4 = 440 Hz, C4 = middle C
midi: number // the nearest note's MIDI number (A4 = 69); `midi % 12` compares across octaves
cents: number // how far the frequency is from that note, −50..50; negative = flat. 0 from midiNote
frequency: number // the frequency of the note itself, Hz
}
AudioRecorder.note(445) // { name: 'A', octave: 4, midi: 69, cents: 20, frequency: 440 }
AudioRecorder.midiNote(60) // { name: 'C', octave: 4, midi: 60, cents: 0, frequency: 261.63 }
AudioRecorder.note(442, 442) // an orchestra tuned to A = 442: cents 0Build a singing game: compare the sung note with a target
To check that the player sings a target note, compare midi % 12 — the note in any octave, since
voices differ — and require it to be held:
const recorder = new AudioRecorder()
const target = AudioRecorder.midiNote(60 + Math.floor(Math.random() * 12)) // a note of the octave of middle C
const prompt = UIText(`Sing ${target.name}`).style({ fontSize: 48, fontWeight: 700 })
const hint = UIText('')
let heldSince = 0
recorder.addEventListener('pitch', p => {
const sung = AudioRecorder.note(p.frequency)
// cents from the target, the octave left out: −600..600
const off = sung ? ((((sung.midi - target.midi) % 12) + 18) % 12 - 6) * 100 + sung.cents : NaN
if (!sung || Math.abs(off) > 30) {
heldSince = 0
hint.text = !sung ? 'Sing or hum it' : off < 0 ? 'Higher' : 'Lower'
return
}
heldSince ||= Date.now()
hint.text = Date.now() - heldSince >= 1000 ? 'Got it!' : 'Hold it…'
})
UIScreen(
prompt, hint,
UIButton(UIText('Start')).onClick(() => { recorder.start({ file: false, raw: true, rate: 30 }).catch(e => { hint.text = e.message }) }),
).style({ pt: 'safe-top', p: 20, gap: 12, alignItems: 'center' }).open()- Time the hold by the clock between events, as above, not by counting events.
- A note is heard about 50 ms after it sounds (the detector listens to that much), plus the device's own input delay, which differs from phone to phone. A game that scores against a song's timeline lets the player calibrate an offset.
- On a phone the microphone hears the phone's own speaker: a game with a backing track needs headphones, or the track is detected instead of the singer.
Listen to the microphone without recording a file: file: false
A tuner, a game or a plain volume meter needs no audio file. With file: false nothing is encoded
or written: only the events fire. stop() (or cancel()) ends it; stop() resolves with
file: null and the duration that was listened to.
const recorder = new AudioRecorder()
const loudness = UIText('…')
recorder.addEventListener('level', v => { loudness.text = `${(20 * Math.log10(Math.max(v, 1e-6))).toFixed(0)} dB` })
UIScreen(
loudness,
UIButton(UIText('Listen')).onClick(() => { recorder.start({ file: false }).catch(e => toast(e.message)) }),
UIButton(UIText('Stop')).onClick(() => { recorder.cancel() }),
).style({ pt: 'safe-top', p: 20, gap: 12 }).open()To record a take AND score it, leave file on and listen to pitch as well: one recording gives
both.
Record music or sing: the raw microphone, raw
By default the microphone is tuned for speech: the system suppresses noise, evens out the volume
and, in a browser, cancels echo. That is right for a voice message and wrong for music — a held
note is treated as noise and fades. raw: true asks for the microphone with as little of that as
the device allows:
const recorder = new AudioRecorder()
const status = UIText('')
const stop = async () => {
const { file, duration } = await recorder.stop()
status.text = `${duration.toFixed(1)} s`
if (file) new AudioPlayer(file).play()
}
UIScreen(
UIButton(UIText('Record the guitar')).onClick(() => { recorder.start({ raw: true, bitrate: 128 }).catch(e => toast(e.message)) }),
UIButton(UIText('Stop')).onClick(() => { stop().catch(e => toast(e.message)) }),
status,
).style({ pt: 'safe-top', p: 20, gap: 12 }).open()| Where | Without raw |
With raw: true |
|---|---|---|
| the web | the browser's noise suppression, gain control and echo cancellation | all three off |
| Android | the phone maker's tuning of the microphone | the unprocessed input where the phone has one, else the lightest |
| iOS | the system's gain and equalization | measurement mode: the least processing iOS has |
A raw recording is quieter than a voice message, and keeps the room's noise.
How often the events fire: rate
rate sets how many times a second level and pitch fire — 10 by default, at most 50. Both
fire on the same tick and describe the same moment.
const recorder = new AudioRecorder()
let events = 0
recorder.addEventListener('pitch', () => { events++ })
setInterval(() => { console.log(`${events} events a second`); events = 0 }, 1000)
UIScreen(
UIButton(UIText('Listen at 30 a second')).onClick(() => { recorder.start({ file: false, rate: 30 }).catch(e => toast(e.message)) }),
).style({ pt: 'safe-top', p: 20, gap: 12 }).open()A higher rate shortens only the wait for the next event (up to 100 ms at 10 a second, 20 ms at 50). It does not shorten the time the detector listens (about 50 ms) or the device's own input delay. 20 is enough for a tuner, 30 for a game.
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:
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 microphone or 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()on iOS and Android maxDuration counts the audio that was recorded, the pauses left
out; on the web it counts from start(), the pauses included.
Pause and resume a recording
pause() holds the recording — the events stop and duration does not grow — and resume()
continues it into the same file:
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).
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:
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):
// 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 })
}// 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()
if (!file) return // only with `file: false`
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.
The app gets the finished file, never the samples: it cannot denoise, trim or normalize a
recording. What decides its sound is chosen before it starts — raw, bitrate, sampleRate.
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, a sampleRate the microphone does not have |
start() |
an Error |
the plugin is not on this host, or a recording is under way |
pause() / resume() |
an Error |
not recording / not paused |
stop() |
'failed' |
nothing could be encoded (a stop right after the start) — never with file: false |
To ask before the first recording, or to send the user to Settings after a refusal, use
permissions (permissions.md):
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
- speech.md —
SpeechRecognizer: speech to text, live - media.md —
AudioPlayer, the playback side - stored-files.md —
Fileparameters andt.file()fields - permissions.md —
permissions.request('microphone'),openSettings() - network.md —
File,FormData