Voice memo

Record a short note from the microphone, listen to it and keep it.

Goal

A voice note for a form, a chat or a lesson: Record asks for the microphone, Pause and Resume hold the clock, Stop turns the take into an audio file you can play and download, and Discard throws it away. A take stops by itself after 60 seconds.

Primitives

  • MediaRecorderController is the recorder: it asks for the microphone, records, and reports one snapshot (status, duration, level) through onState, so the recipe never touches getUserMedia, MediaRecorder or a track. A refused permission is the denied status and a browser without the APIs is unsupported, so neither is an exception. It stops by itself at maxDuration, stops every track when the take ends, is discarded or the element leaves, and revokes the result's object URL on the next start(), on discard() and on destroy().
  • formatMediaTime formats the clock, from the media time helpers.

The buttons are design-system buttons: icon buttons named Record, Pause (Resume while paused), Stop and Discard, and the download is a button-styled link.

Left to the recipe: mapping the snapshot to what is drawn (viewOf in voice-memo.data, one pure function every form shares, so they cannot disagree), the status line, the level meter and the player. The status is a polite live region and says each of the eight states: idle, requesting, recording, paused, stopped, denied (with how to try again), unsupported and error, and says when the 60 second limit ended the take.

The level meter uses the recorder's own level, which it measures when it is given getAudioContext, in place of an AudioVisualizerController fed with getStream(). The meter is one number from 0 to 1, which the recorder already reports with every onState, so a second controller, a second analyser and a canvas would add nothing; use the visualizer when you want bars or a wave. The recipe creates the AudioContext inside getAudioContext, which runs in start() from the click, and closes it with the memo. The stream is only read by an analyser that is connected to nothing, never to the speakers, so there is no feedback.

Example

Press Record and allow the microphone. Speak and watch the meter, pause and resume, then stop: the take appears in an audio player with a Download link. Press Record again to make a new one, or Discard to drop it. If you block the microphone, the status explains how to allow it and try again.

Pick an authoring pattern below; they all behave the same, and the one you pick is remembered on the other recipes.

The same behavior as a RadiantElement. The markup is authored inside the element; there is nothing to mount, clean up or run again.

0:00

Press Record to start. It stops by itself after 1:00.

import { RadiantElement, customElement, onEvent, query } from '@ecopages/radiant';
import { createMediaRecorderController } from '@ecopages/radiant-ui/controllers';
import { MeterContext, createRecorderConfig, paint, showResult, viewOf } from './voice-memo.data';

/**
 * @remarks
 * The authored markup is the element's content, and `paint` writes every state change onto it. The recorder is
 * created with the element as its host, so it attaches when the element connects and is destroyed, with its
 * tracks stopped and its result URL revoked, when it leaves. The meter's `AudioContext` is closed by the cleanup
 * registered once in the constructor, because one registered in `onConnected` would be added again on every move.
 */
@customElement('voice-memo-element')
export class VoiceMemoElement extends RadiantElement {
	@query({ selector: '[data-player]' }) private player!: HTMLAudioElement;

	private readonly meter = new MeterContext();

	private readonly recorder = createMediaRecorderController(
		this,
		createRecorderConfig(this.meter, {
			onState: (snapshot) => paint(this, viewOf(snapshot)),
			onStop: (result) => showResult(this, result),
		}),
	);

	constructor() {
		super();
		this.registerCleanupCallback(() => {
			showResult(this, null);
			this.meter.close();
		});
	}

	override onConnected(): void {
		paint(this, viewOf(this.recorder.getState()));
	}

	@onEvent({ selector: '[data-record]', type: 'click' })
	record(): void {
		showResult(this, null);
		void this.recorder.start();
	}

	@onEvent({ selector: '[data-pause]', type: 'click' })
	togglePause(): void {
		if (this.recorder.getState().status === 'paused') this.recorder.resume();
		else this.recorder.pause();
	}

	@onEvent({ selector: '[data-stop]', type: 'click' })
	stop(): void {
		void this.recorder.stop();
	}

	@onEvent({ selector: '[data-discard]', type: 'click' })
	discard(): void {
		showResult(this, null);
		this.recorder.discard();
	}
}

createMediaRecorderController(this, ...) attaches the recorder when the element connects and destroys it when it leaves, which stops the microphone and revokes the URL. @onEvent delegates the four clicks. The player's source is cleared before start() and discard(), because the recorder revokes the previous URL there and an audio element that still held it would fail. A callback registered once in the constructor with registerCleanupCallback clears the player and closes the audio context; one registered in onConnected would be added again on every move.

Styles

The state is data-state on the status line and the meter, so the stylesheet needs no class the script would keep in step: the meter is a bar scaled by --level, dimmed unless the state is recording, and a blocked, failed or unsupported state colours the status with the error token. Every colour is a theme token, so it follows the selected theme in light and dark, and the controls wrap at a phone width.