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) throughonState, so the recipe never touchesgetUserMedia,MediaRecorderor a track. A refused permission is thedeniedstatus and a browser without the APIs isunsupported, so neither is an exception. It stops by itself atmaxDuration, stops every track when the take ends, is discarded or the element leaves, and revokes the result's object URL on the nextstart(), ondiscard()and ondestroy(). formatMediaTimeformats 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.
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();
}
}import { formatMediaTime } from '@ecopages/radiant-ui/helpers';
import type {
MediaRecorderControllerConfig,
MediaRecorderSnapshot,
MediaRecorderStatus,
MediaRecordingResult,
} from '@ecopages/radiant-ui/controllers';
/** Seconds after which the recorder stops by itself. */
export const MAX_DURATION = 60;
export const MIME_TYPES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg;codecs=opus'];
const LIMIT_TEXT = formatMediaTime(MAX_DURATION);
/** What a form draws for one recorder snapshot, so every form shows the same thing. */
export type VoiceMemoView = {
state: MediaRecorderStatus;
status: string;
elapsed: string;
/** Loudness from 0 to 1. */
level: number;
record: boolean;
pause: boolean;
stop: boolean;
discard: boolean;
/** The recording is paused, so the pause button resumes. */
paused: boolean;
/** There is a recording to play and download. */
result: boolean;
};
function statusText(snapshot: MediaRecorderSnapshot): string {
switch (snapshot.status) {
case 'idle':
return `Press Record to start. It stops by itself after ${LIMIT_TEXT}.`;
case 'requesting':
return 'Waiting for permission to use the microphone.';
case 'recording':
return `Recording. It stops by itself at ${LIMIT_TEXT}.`;
case 'paused':
return 'Paused. Press Resume to go on, or Stop to finish.';
case 'stopped':
return snapshot.duration >= MAX_DURATION - 0.5
? `Stopped at the ${LIMIT_TEXT} limit. Play it back, download it or discard it.`
: `Recorded ${formatMediaTime(snapshot.duration)}. Play it back, download it or discard it.`;
case 'denied':
return 'Microphone access is blocked. Allow the microphone for this site in the browser settings, then press Record to try again.';
case 'unsupported':
return 'This browser cannot record audio.';
case 'error':
return 'Recording failed. Press Record to try again.';
}
}
/** Maps a recorder snapshot to what the controls, the clock, the meter and the status line show. */
export function viewOf(snapshot: MediaRecorderSnapshot): VoiceMemoView {
const { status } = snapshot;
const live = status === 'recording' || status === 'paused';
return {
state: status,
status: statusText(snapshot),
elapsed: formatMediaTime(snapshot.duration),
level: snapshot.level,
record: status === 'idle' || status === 'stopped' || status === 'denied' || status === 'error',
pause: live,
stop: live,
discard: live || status === 'stopped',
paused: status === 'paused',
result: status === 'stopped',
};
}
function extensionOf(mimeType: string): string {
const subtype = mimeType.split(';')[0].split('/')[1] ?? 'webm';
return subtype === 'mp4' ? 'm4a' : subtype;
}
/**
* The recorder's settings, shared by every form.
*
* @remarks
* The level meter needs an `AudioContext`. `getAudioContext` runs inside `start()`, which a click calls, so the
* context is created and resumed inside that gesture. The recorder only reads the stream into an analyser and never
* connects it to the speakers.
*/
export function createRecorderConfig(
context: MeterContext,
config: Pick<MediaRecorderControllerConfig, 'onState' | 'onStop'>,
): MediaRecorderControllerConfig {
return {
mimeTypes: MIME_TYPES,
maxDuration: MAX_DURATION,
timeslice: 250,
getAudioContext: () => context.get(),
...config,
};
}
/** One `AudioContext` for the life of a memo, created on first use and closed with it. */
export class MeterContext {
private context: AudioContext | null = null;
get(): AudioContext {
this.context ??= new AudioContext();
void this.context.resume();
return this.context;
}
close(): void {
void this.context?.close();
this.context = null;
}
}
/**
* Draws a view into the markup of a plain, element or controller form: `data-state` on the root, the status line and
* the meter (the stylesheet selects on the ones it styles), the clock and the four buttons.
*/
export function paint(root: HTMLElement, view: VoiceMemoView): void {
const part = <T extends HTMLElement>(selector: string) => root.querySelector<T>(selector)!;
root.dataset.state = view.state;
part('[data-status]').textContent = view.status;
part('[data-status]').dataset.state = view.state;
part('[data-elapsed]').textContent = view.elapsed;
part('[data-meter]').dataset.state = view.state;
part('[data-meter]').style.setProperty('--level', view.level.toFixed(2));
part<HTMLButtonElement>('[data-record]').disabled = !view.record;
part<HTMLButtonElement>('[data-stop]').disabled = !view.stop;
part<HTMLButtonElement>('[data-discard]').disabled = !view.discard;
const pause = part<HTMLButtonElement>('[data-pause]');
pause.disabled = !view.pause;
pause.setAttribute('aria-label', view.paused ? 'Resume' : 'Pause');
pause.toggleAttribute('data-paused', view.paused);
part('[data-result]').hidden = !view.result;
}
/**
* Points the player and the download link at a result, or clears them.
*
* @remarks
* The recorder revokes the URL of a result on the next `start()`, on `discard()` and on `destroy()`, so the player
* is cleared before any of them: its `src` is removed and `load()` drops the media.
*/
export function showResult(root: HTMLElement, result: MediaRecordingResult | null): void {
const player = root.querySelector<HTMLAudioElement>('[data-player]')!;
const link = root.querySelector<HTMLAnchorElement>('[data-download]')!;
if (result) {
player.src = result.url;
link.href = result.url;
link.download = `voice-memo.${extensionOf(result.mimeType)}`;
return;
}
player.removeAttribute('src');
player.load();
link.removeAttribute('href');
}<voice-memo-element data-state="idle">
<div data-meter aria-hidden="true"><span></span></div>
<output data-elapsed>0:00</output>
<div data-controls>
<button
type="button"
class="rui-button rui-button--filled rui-button--lg rui-button--square"
data-record
aria-label="Record"
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<circle cx="12" cy="12" r="6" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-pause
aria-label="Pause"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="pause">
<path d="M7 5h3v14H7zM14 5h3v14h-3z" fill="currentColor" />
</svg>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="resume">
<path d="M8 5v14l10-7z" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-stop
aria-label="Stop"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<path d="M7 7h10v10H7z" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-discard
aria-label="Discard"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<path
d="M5 7h14M10 7V5h4v2M7 7l1 12h8l1-12"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
</div>
<div data-result hidden>
<audio data-player controls preload="auto"></audio>
<a class="rui-button rui-button--outline rui-button--sm" data-download download="voice-memo.webm">Download</a>
</div>
<p data-status aria-live="polite">Press Record to start. It stops by itself after 1:00.</p>
</voice-memo-element>.primitive-example:is(
[data-example='voice-memo'],
:has(> voice-memo-element, > [data-controller='voice-memo'], > voice-memo-app)
) {
display: flex;
flex-direction: column;
align-items: stretch;
gap: var(--space-stack);
box-sizing: border-box;
width: min(100%, 24rem);
padding: var(--space-inset);
border: 1px solid var(--border);
border-radius: var(--radius-container);
background: var(--surface);
color: var(--on-surface);
box-shadow: var(--shadow-overlay);
--voice-memo-muted: color-mix(in srgb, currentColor 78%, var(--surface));
& :where(voice-memo-element, [data-controller='voice-memo'], voice-memo-app) {
display: flex;
flex-direction: column;
gap: var(--space-stack);
min-width: 0;
}
& :where([data-meter]) {
position: relative;
height: 0.5rem;
overflow: hidden;
border-radius: var(--radius-full);
background: var(--surface-container-high);
& > span {
position: absolute;
inset: 0;
transform: scaleX(var(--level, 0));
transform-origin: left center;
border-radius: inherit;
background: var(--primary);
transition: transform 90ms linear;
}
}
& :where([data-meter]:not([data-state='recording']) > span) {
opacity: 0.4;
}
& :where([data-elapsed]) {
font-size: 2rem;
line-height: 1;
font-variant-numeric: tabular-nums;
}
& :where([data-controls]) {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
}
& [data-pause] [data-icon='resume'],
& [data-pause][data-paused] [data-icon='pause'] {
display: none;
}
& [data-pause][data-paused] [data-icon='resume'] {
display: block;
}
& :where([data-result]) {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
& > audio {
flex: 1 1 12rem;
min-width: 0;
width: 100%;
}
}
& :where([data-result][hidden]) {
display: none;
}
& :where([data-status]) {
margin: 0;
font-size: 0.8125rem;
color: var(--voice-memo-muted);
}
& :where([data-status]:is([data-state='denied'], [data-state='error'], [data-state='unsupported'])) {
color: var(--error);
font-weight: 500;
}
}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.
The same behavior as a RadiantElement. The markup is authored inside the element; there is nothing to mount, clean up or run again.
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();
}
}import { formatMediaTime } from '@ecopages/radiant-ui/helpers';
import type {
MediaRecorderControllerConfig,
MediaRecorderSnapshot,
MediaRecorderStatus,
MediaRecordingResult,
} from '@ecopages/radiant-ui/controllers';
/** Seconds after which the recorder stops by itself. */
export const MAX_DURATION = 60;
export const MIME_TYPES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg;codecs=opus'];
const LIMIT_TEXT = formatMediaTime(MAX_DURATION);
/** What a form draws for one recorder snapshot, so every form shows the same thing. */
export type VoiceMemoView = {
state: MediaRecorderStatus;
status: string;
elapsed: string;
/** Loudness from 0 to 1. */
level: number;
record: boolean;
pause: boolean;
stop: boolean;
discard: boolean;
/** The recording is paused, so the pause button resumes. */
paused: boolean;
/** There is a recording to play and download. */
result: boolean;
};
function statusText(snapshot: MediaRecorderSnapshot): string {
switch (snapshot.status) {
case 'idle':
return `Press Record to start. It stops by itself after ${LIMIT_TEXT}.`;
case 'requesting':
return 'Waiting for permission to use the microphone.';
case 'recording':
return `Recording. It stops by itself at ${LIMIT_TEXT}.`;
case 'paused':
return 'Paused. Press Resume to go on, or Stop to finish.';
case 'stopped':
return snapshot.duration >= MAX_DURATION - 0.5
? `Stopped at the ${LIMIT_TEXT} limit. Play it back, download it or discard it.`
: `Recorded ${formatMediaTime(snapshot.duration)}. Play it back, download it or discard it.`;
case 'denied':
return 'Microphone access is blocked. Allow the microphone for this site in the browser settings, then press Record to try again.';
case 'unsupported':
return 'This browser cannot record audio.';
case 'error':
return 'Recording failed. Press Record to try again.';
}
}
/** Maps a recorder snapshot to what the controls, the clock, the meter and the status line show. */
export function viewOf(snapshot: MediaRecorderSnapshot): VoiceMemoView {
const { status } = snapshot;
const live = status === 'recording' || status === 'paused';
return {
state: status,
status: statusText(snapshot),
elapsed: formatMediaTime(snapshot.duration),
level: snapshot.level,
record: status === 'idle' || status === 'stopped' || status === 'denied' || status === 'error',
pause: live,
stop: live,
discard: live || status === 'stopped',
paused: status === 'paused',
result: status === 'stopped',
};
}
function extensionOf(mimeType: string): string {
const subtype = mimeType.split(';')[0].split('/')[1] ?? 'webm';
return subtype === 'mp4' ? 'm4a' : subtype;
}
/**
* The recorder's settings, shared by every form.
*
* @remarks
* The level meter needs an `AudioContext`. `getAudioContext` runs inside `start()`, which a click calls, so the
* context is created and resumed inside that gesture. The recorder only reads the stream into an analyser and never
* connects it to the speakers.
*/
export function createRecorderConfig(
context: MeterContext,
config: Pick<MediaRecorderControllerConfig, 'onState' | 'onStop'>,
): MediaRecorderControllerConfig {
return {
mimeTypes: MIME_TYPES,
maxDuration: MAX_DURATION,
timeslice: 250,
getAudioContext: () => context.get(),
...config,
};
}
/** One `AudioContext` for the life of a memo, created on first use and closed with it. */
export class MeterContext {
private context: AudioContext | null = null;
get(): AudioContext {
this.context ??= new AudioContext();
void this.context.resume();
return this.context;
}
close(): void {
void this.context?.close();
this.context = null;
}
}
/**
* Draws a view into the markup of a plain, element or controller form: `data-state` on the root, the status line and
* the meter (the stylesheet selects on the ones it styles), the clock and the four buttons.
*/
export function paint(root: HTMLElement, view: VoiceMemoView): void {
const part = <T extends HTMLElement>(selector: string) => root.querySelector<T>(selector)!;
root.dataset.state = view.state;
part('[data-status]').textContent = view.status;
part('[data-status]').dataset.state = view.state;
part('[data-elapsed]').textContent = view.elapsed;
part('[data-meter]').dataset.state = view.state;
part('[data-meter]').style.setProperty('--level', view.level.toFixed(2));
part<HTMLButtonElement>('[data-record]').disabled = !view.record;
part<HTMLButtonElement>('[data-stop]').disabled = !view.stop;
part<HTMLButtonElement>('[data-discard]').disabled = !view.discard;
const pause = part<HTMLButtonElement>('[data-pause]');
pause.disabled = !view.pause;
pause.setAttribute('aria-label', view.paused ? 'Resume' : 'Pause');
pause.toggleAttribute('data-paused', view.paused);
part('[data-result]').hidden = !view.result;
}
/**
* Points the player and the download link at a result, or clears them.
*
* @remarks
* The recorder revokes the URL of a result on the next `start()`, on `discard()` and on `destroy()`, so the player
* is cleared before any of them: its `src` is removed and `load()` drops the media.
*/
export function showResult(root: HTMLElement, result: MediaRecordingResult | null): void {
const player = root.querySelector<HTMLAudioElement>('[data-player]')!;
const link = root.querySelector<HTMLAnchorElement>('[data-download]')!;
if (result) {
player.src = result.url;
link.href = result.url;
link.download = `voice-memo.${extensionOf(result.mimeType)}`;
return;
}
player.removeAttribute('src');
player.load();
link.removeAttribute('href');
}<voice-memo-element data-state="idle">
<div data-meter aria-hidden="true"><span></span></div>
<output data-elapsed>0:00</output>
<div data-controls>
<button
type="button"
class="rui-button rui-button--filled rui-button--lg rui-button--square"
data-record
aria-label="Record"
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<circle cx="12" cy="12" r="6" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-pause
aria-label="Pause"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="pause">
<path d="M7 5h3v14H7zM14 5h3v14h-3z" fill="currentColor" />
</svg>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="resume">
<path d="M8 5v14l10-7z" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-stop
aria-label="Stop"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<path d="M7 7h10v10H7z" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-discard
aria-label="Discard"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<path
d="M5 7h14M10 7V5h4v2M7 7l1 12h8l1-12"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
</div>
<div data-result hidden>
<audio data-player controls preload="auto"></audio>
<a class="rui-button rui-button--outline rui-button--sm" data-download download="voice-memo.webm">Download</a>
</div>
<p data-status aria-live="polite">Press Record to start. It stops by itself after 1:00.</p>
</voice-memo-element>.primitive-example:is(
[data-example='voice-memo'],
:has(> voice-memo-element, > [data-controller='voice-memo'], > voice-memo-app)
) {
display: flex;
flex-direction: column;
align-items: stretch;
gap: var(--space-stack);
box-sizing: border-box;
width: min(100%, 24rem);
padding: var(--space-inset);
border: 1px solid var(--border);
border-radius: var(--radius-container);
background: var(--surface);
color: var(--on-surface);
box-shadow: var(--shadow-overlay);
--voice-memo-muted: color-mix(in srgb, currentColor 78%, var(--surface));
& :where(voice-memo-element, [data-controller='voice-memo'], voice-memo-app) {
display: flex;
flex-direction: column;
gap: var(--space-stack);
min-width: 0;
}
& :where([data-meter]) {
position: relative;
height: 0.5rem;
overflow: hidden;
border-radius: var(--radius-full);
background: var(--surface-container-high);
& > span {
position: absolute;
inset: 0;
transform: scaleX(var(--level, 0));
transform-origin: left center;
border-radius: inherit;
background: var(--primary);
transition: transform 90ms linear;
}
}
& :where([data-meter]:not([data-state='recording']) > span) {
opacity: 0.4;
}
& :where([data-elapsed]) {
font-size: 2rem;
line-height: 1;
font-variant-numeric: tabular-nums;
}
& :where([data-controls]) {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
}
& [data-pause] [data-icon='resume'],
& [data-pause][data-paused] [data-icon='pause'] {
display: none;
}
& [data-pause][data-paused] [data-icon='resume'] {
display: block;
}
& :where([data-result]) {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
& > audio {
flex: 1 1 12rem;
min-width: 0;
width: 100%;
}
}
& :where([data-result][hidden]) {
display: none;
}
& :where([data-status]) {
margin: 0;
font-size: 0.8125rem;
color: var(--voice-memo-muted);
}
& :where([data-status]:is([data-state='denied'], [data-state='error'], [data-state='unsupported'])) {
color: var(--error);
font-weight: 500;
}
}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.
The same behavior as a single RadiantElement that owns its markup: the view of the recorder is @state and render() draws the buttons, the clock and the status.
import { RadiantElement, customElement, onEvent, query, state } from '@ecopages/radiant';
import { createMediaRecorderController } from '@ecopages/radiant-ui/controllers';
import { RuiButton } from '@ecopages/radiant-ui/button';
import { MeterContext, createRecorderConfig, showResult, viewOf, type VoiceMemoView } from './voice-memo.data';
/**
* @remarks
* The view of the recorder is one `@state`, and `render()` draws the four buttons, the clock, the meter and the
* status from it. The loudness changes about ten times a second, so it is written to the meter by hand instead of
* redrawing the controls. The player and the download link are not state: their `src` and `href` are the recorder's
* object URL, which the recorder revokes on the next `start()`, so they are written and cleared by hand around it.
*/
@customElement('voice-memo-app')
export class VoiceMemoApp extends RadiantElement {
@state view: VoiceMemoView = viewOf({ status: 'idle', duration: 0, mimeType: null, level: 0, error: null });
@query({ selector: '[data-meter]' }) private meterNode!: HTMLElement;
private readonly meter = new MeterContext();
private readonly recorder = createMediaRecorderController(
this,
createRecorderConfig(this.meter, {
onState: (snapshot) => this.show(viewOf(snapshot)),
onStop: (result) => showResult(this, result),
}),
);
constructor() {
super();
this.registerCleanupCallback(() => {
showResult(this, null);
this.meter.close();
});
}
private shown = '';
private show(view: VoiceMemoView): void {
this.meterNode?.style.setProperty('--level', view.level.toFixed(2));
const key = JSON.stringify({ ...view, level: 0 });
if (key !== this.shown) {
this.shown = key;
this.view = view;
}
}
@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();
}
override render() {
const { view } = this;
return (
<>
<div data-meter aria-hidden="true" data-state={view.state}>
<span></span>
</div>
<output data-elapsed>{view.elapsed}</output>
<div data-controls>
<RuiButton size="lg" square data-record aria-label="Record" disabled={!view.record}>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<circle cx="12" cy="12" r="6" fill="currentColor" />
</svg>
</RuiButton>
<RuiButton
variant="ghost"
square
data-pause
data-paused={view.paused ? '' : undefined}
aria-label={view.paused ? 'Resume' : 'Pause'}
disabled={!view.pause}
>
<svg
viewBox="0 0 24 24"
width="16"
height="16"
aria-hidden="true"
focusable="false"
data-icon="pause"
>
<path d="M7 5h3v14H7zM14 5h3v14h-3z" fill="currentColor" />
</svg>
<svg
viewBox="0 0 24 24"
width="16"
height="16"
aria-hidden="true"
focusable="false"
data-icon="resume"
>
<path d="M8 5v14l10-7z" fill="currentColor" />
</svg>
</RuiButton>
<RuiButton variant="ghost" square data-stop aria-label="Stop" disabled={!view.stop}>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<path d="M7 7h10v10H7z" fill="currentColor" />
</svg>
</RuiButton>
<RuiButton variant="ghost" square data-discard aria-label="Discard" disabled={!view.discard}>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<path
d="M5 7h14M10 7V5h4v2M7 7l1 12h8l1-12"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</RuiButton>
</div>
<div data-result hidden={!view.result}>
<audio data-player controls preload="auto"></audio>
<a class="rui-button rui-button--outline rui-button--sm" data-download download="voice-memo.webm">
Download
</a>
</div>
<p data-status aria-live="polite" data-state={view.state}>
{view.status}
</p>
</>
);
}
}import { formatMediaTime } from '@ecopages/radiant-ui/helpers';
import type {
MediaRecorderControllerConfig,
MediaRecorderSnapshot,
MediaRecorderStatus,
MediaRecordingResult,
} from '@ecopages/radiant-ui/controllers';
/** Seconds after which the recorder stops by itself. */
export const MAX_DURATION = 60;
export const MIME_TYPES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg;codecs=opus'];
const LIMIT_TEXT = formatMediaTime(MAX_DURATION);
/** What a form draws for one recorder snapshot, so every form shows the same thing. */
export type VoiceMemoView = {
state: MediaRecorderStatus;
status: string;
elapsed: string;
/** Loudness from 0 to 1. */
level: number;
record: boolean;
pause: boolean;
stop: boolean;
discard: boolean;
/** The recording is paused, so the pause button resumes. */
paused: boolean;
/** There is a recording to play and download. */
result: boolean;
};
function statusText(snapshot: MediaRecorderSnapshot): string {
switch (snapshot.status) {
case 'idle':
return `Press Record to start. It stops by itself after ${LIMIT_TEXT}.`;
case 'requesting':
return 'Waiting for permission to use the microphone.';
case 'recording':
return `Recording. It stops by itself at ${LIMIT_TEXT}.`;
case 'paused':
return 'Paused. Press Resume to go on, or Stop to finish.';
case 'stopped':
return snapshot.duration >= MAX_DURATION - 0.5
? `Stopped at the ${LIMIT_TEXT} limit. Play it back, download it or discard it.`
: `Recorded ${formatMediaTime(snapshot.duration)}. Play it back, download it or discard it.`;
case 'denied':
return 'Microphone access is blocked. Allow the microphone for this site in the browser settings, then press Record to try again.';
case 'unsupported':
return 'This browser cannot record audio.';
case 'error':
return 'Recording failed. Press Record to try again.';
}
}
/** Maps a recorder snapshot to what the controls, the clock, the meter and the status line show. */
export function viewOf(snapshot: MediaRecorderSnapshot): VoiceMemoView {
const { status } = snapshot;
const live = status === 'recording' || status === 'paused';
return {
state: status,
status: statusText(snapshot),
elapsed: formatMediaTime(snapshot.duration),
level: snapshot.level,
record: status === 'idle' || status === 'stopped' || status === 'denied' || status === 'error',
pause: live,
stop: live,
discard: live || status === 'stopped',
paused: status === 'paused',
result: status === 'stopped',
};
}
function extensionOf(mimeType: string): string {
const subtype = mimeType.split(';')[0].split('/')[1] ?? 'webm';
return subtype === 'mp4' ? 'm4a' : subtype;
}
/**
* The recorder's settings, shared by every form.
*
* @remarks
* The level meter needs an `AudioContext`. `getAudioContext` runs inside `start()`, which a click calls, so the
* context is created and resumed inside that gesture. The recorder only reads the stream into an analyser and never
* connects it to the speakers.
*/
export function createRecorderConfig(
context: MeterContext,
config: Pick<MediaRecorderControllerConfig, 'onState' | 'onStop'>,
): MediaRecorderControllerConfig {
return {
mimeTypes: MIME_TYPES,
maxDuration: MAX_DURATION,
timeslice: 250,
getAudioContext: () => context.get(),
...config,
};
}
/** One `AudioContext` for the life of a memo, created on first use and closed with it. */
export class MeterContext {
private context: AudioContext | null = null;
get(): AudioContext {
this.context ??= new AudioContext();
void this.context.resume();
return this.context;
}
close(): void {
void this.context?.close();
this.context = null;
}
}
/**
* Draws a view into the markup of a plain, element or controller form: `data-state` on the root, the status line and
* the meter (the stylesheet selects on the ones it styles), the clock and the four buttons.
*/
export function paint(root: HTMLElement, view: VoiceMemoView): void {
const part = <T extends HTMLElement>(selector: string) => root.querySelector<T>(selector)!;
root.dataset.state = view.state;
part('[data-status]').textContent = view.status;
part('[data-status]').dataset.state = view.state;
part('[data-elapsed]').textContent = view.elapsed;
part('[data-meter]').dataset.state = view.state;
part('[data-meter]').style.setProperty('--level', view.level.toFixed(2));
part<HTMLButtonElement>('[data-record]').disabled = !view.record;
part<HTMLButtonElement>('[data-stop]').disabled = !view.stop;
part<HTMLButtonElement>('[data-discard]').disabled = !view.discard;
const pause = part<HTMLButtonElement>('[data-pause]');
pause.disabled = !view.pause;
pause.setAttribute('aria-label', view.paused ? 'Resume' : 'Pause');
pause.toggleAttribute('data-paused', view.paused);
part('[data-result]').hidden = !view.result;
}
/**
* Points the player and the download link at a result, or clears them.
*
* @remarks
* The recorder revokes the URL of a result on the next `start()`, on `discard()` and on `destroy()`, so the player
* is cleared before any of them: its `src` is removed and `load()` drops the media.
*/
export function showResult(root: HTMLElement, result: MediaRecordingResult | null): void {
const player = root.querySelector<HTMLAudioElement>('[data-player]')!;
const link = root.querySelector<HTMLAnchorElement>('[data-download]')!;
if (result) {
player.src = result.url;
link.href = result.url;
link.download = `voice-memo.${extensionOf(result.mimeType)}`;
return;
}
player.removeAttribute('src');
player.load();
link.removeAttribute('href');
}.primitive-example:is(
[data-example='voice-memo'],
:has(> voice-memo-element, > [data-controller='voice-memo'], > voice-memo-app)
) {
display: flex;
flex-direction: column;
align-items: stretch;
gap: var(--space-stack);
box-sizing: border-box;
width: min(100%, 24rem);
padding: var(--space-inset);
border: 1px solid var(--border);
border-radius: var(--radius-container);
background: var(--surface);
color: var(--on-surface);
box-shadow: var(--shadow-overlay);
--voice-memo-muted: color-mix(in srgb, currentColor 78%, var(--surface));
& :where(voice-memo-element, [data-controller='voice-memo'], voice-memo-app) {
display: flex;
flex-direction: column;
gap: var(--space-stack);
min-width: 0;
}
& :where([data-meter]) {
position: relative;
height: 0.5rem;
overflow: hidden;
border-radius: var(--radius-full);
background: var(--surface-container-high);
& > span {
position: absolute;
inset: 0;
transform: scaleX(var(--level, 0));
transform-origin: left center;
border-radius: inherit;
background: var(--primary);
transition: transform 90ms linear;
}
}
& :where([data-meter]:not([data-state='recording']) > span) {
opacity: 0.4;
}
& :where([data-elapsed]) {
font-size: 2rem;
line-height: 1;
font-variant-numeric: tabular-nums;
}
& :where([data-controls]) {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
}
& [data-pause] [data-icon='resume'],
& [data-pause][data-paused] [data-icon='pause'] {
display: none;
}
& [data-pause][data-paused] [data-icon='resume'] {
display: block;
}
& :where([data-result]) {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
& > audio {
flex: 1 1 12rem;
min-width: 0;
width: 100%;
}
}
& :where([data-result][hidden]) {
display: none;
}
& :where([data-status]) {
margin: 0;
font-size: 0.8125rem;
color: var(--voice-memo-muted);
}
& :where([data-status]:is([data-state='denied'], [data-state='error'], [data-state='unsupported'])) {
color: var(--error);
font-weight: 500;
}
}onState fires about ten times a second while recording, so the component redraws only when something other than the level changed: the clock, the status or which buttons are enabled. The level is written to the meter's --level by hand. The player and the link are written by showResult and not by render(), since their value is an object URL the recorder owns. Compared with the element, the markup lives in the class and the buttons are RuiButtons, but the server renders the tag empty and the client draws it.
The same behavior as a RadiantController attached to the authored markup, which carries data-controller="voice-memo" on a plain div.
import { RadiantController, controller, onEvent } from '@ecopages/radiant';
import { createMediaRecorderController } from '@ecopages/radiant-ui/controllers';
import { MeterContext, createRecorderConfig, paint, showResult, viewOf } from './voice-memo.data';
/**
* @remarks
* The element form's logic on a `RadiantController`, with `connect()` in place of `onConnected()`. `this.element` is the
* host the markup carries `data-controller` on, and `createMediaRecorderController(this, ...)` takes the controller as
* its host, so the recorder attaches when the registry connects it and is destroyed when it disconnects.
*/
@controller('voice-memo')
export class VoiceMemoController extends RadiantController {
private get root(): HTMLElement {
return this.element as HTMLElement;
}
private readonly meter = new MeterContext();
private readonly recorder = createMediaRecorderController(
this,
createRecorderConfig(this.meter, {
onState: (snapshot) => paint(this.root, viewOf(snapshot)),
onStop: (result) => showResult(this.root, result),
}),
);
constructor(host: Element) {
super(host);
this.registerCleanupCallback(() => {
showResult(this.root, null);
this.meter.close();
});
}
override connect(): void {
super.connect();
paint(this.root, viewOf(this.recorder.getState()));
}
@onEvent({ selector: '[data-record]', type: 'click' })
record(): void {
showResult(this.root, 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.root, null);
this.recorder.discard();
}
}import { formatMediaTime } from '@ecopages/radiant-ui/helpers';
import type {
MediaRecorderControllerConfig,
MediaRecorderSnapshot,
MediaRecorderStatus,
MediaRecordingResult,
} from '@ecopages/radiant-ui/controllers';
/** Seconds after which the recorder stops by itself. */
export const MAX_DURATION = 60;
export const MIME_TYPES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg;codecs=opus'];
const LIMIT_TEXT = formatMediaTime(MAX_DURATION);
/** What a form draws for one recorder snapshot, so every form shows the same thing. */
export type VoiceMemoView = {
state: MediaRecorderStatus;
status: string;
elapsed: string;
/** Loudness from 0 to 1. */
level: number;
record: boolean;
pause: boolean;
stop: boolean;
discard: boolean;
/** The recording is paused, so the pause button resumes. */
paused: boolean;
/** There is a recording to play and download. */
result: boolean;
};
function statusText(snapshot: MediaRecorderSnapshot): string {
switch (snapshot.status) {
case 'idle':
return `Press Record to start. It stops by itself after ${LIMIT_TEXT}.`;
case 'requesting':
return 'Waiting for permission to use the microphone.';
case 'recording':
return `Recording. It stops by itself at ${LIMIT_TEXT}.`;
case 'paused':
return 'Paused. Press Resume to go on, or Stop to finish.';
case 'stopped':
return snapshot.duration >= MAX_DURATION - 0.5
? `Stopped at the ${LIMIT_TEXT} limit. Play it back, download it or discard it.`
: `Recorded ${formatMediaTime(snapshot.duration)}. Play it back, download it or discard it.`;
case 'denied':
return 'Microphone access is blocked. Allow the microphone for this site in the browser settings, then press Record to try again.';
case 'unsupported':
return 'This browser cannot record audio.';
case 'error':
return 'Recording failed. Press Record to try again.';
}
}
/** Maps a recorder snapshot to what the controls, the clock, the meter and the status line show. */
export function viewOf(snapshot: MediaRecorderSnapshot): VoiceMemoView {
const { status } = snapshot;
const live = status === 'recording' || status === 'paused';
return {
state: status,
status: statusText(snapshot),
elapsed: formatMediaTime(snapshot.duration),
level: snapshot.level,
record: status === 'idle' || status === 'stopped' || status === 'denied' || status === 'error',
pause: live,
stop: live,
discard: live || status === 'stopped',
paused: status === 'paused',
result: status === 'stopped',
};
}
function extensionOf(mimeType: string): string {
const subtype = mimeType.split(';')[0].split('/')[1] ?? 'webm';
return subtype === 'mp4' ? 'm4a' : subtype;
}
/**
* The recorder's settings, shared by every form.
*
* @remarks
* The level meter needs an `AudioContext`. `getAudioContext` runs inside `start()`, which a click calls, so the
* context is created and resumed inside that gesture. The recorder only reads the stream into an analyser and never
* connects it to the speakers.
*/
export function createRecorderConfig(
context: MeterContext,
config: Pick<MediaRecorderControllerConfig, 'onState' | 'onStop'>,
): MediaRecorderControllerConfig {
return {
mimeTypes: MIME_TYPES,
maxDuration: MAX_DURATION,
timeslice: 250,
getAudioContext: () => context.get(),
...config,
};
}
/** One `AudioContext` for the life of a memo, created on first use and closed with it. */
export class MeterContext {
private context: AudioContext | null = null;
get(): AudioContext {
this.context ??= new AudioContext();
void this.context.resume();
return this.context;
}
close(): void {
void this.context?.close();
this.context = null;
}
}
/**
* Draws a view into the markup of a plain, element or controller form: `data-state` on the root, the status line and
* the meter (the stylesheet selects on the ones it styles), the clock and the four buttons.
*/
export function paint(root: HTMLElement, view: VoiceMemoView): void {
const part = <T extends HTMLElement>(selector: string) => root.querySelector<T>(selector)!;
root.dataset.state = view.state;
part('[data-status]').textContent = view.status;
part('[data-status]').dataset.state = view.state;
part('[data-elapsed]').textContent = view.elapsed;
part('[data-meter]').dataset.state = view.state;
part('[data-meter]').style.setProperty('--level', view.level.toFixed(2));
part<HTMLButtonElement>('[data-record]').disabled = !view.record;
part<HTMLButtonElement>('[data-stop]').disabled = !view.stop;
part<HTMLButtonElement>('[data-discard]').disabled = !view.discard;
const pause = part<HTMLButtonElement>('[data-pause]');
pause.disabled = !view.pause;
pause.setAttribute('aria-label', view.paused ? 'Resume' : 'Pause');
pause.toggleAttribute('data-paused', view.paused);
part('[data-result]').hidden = !view.result;
}
/**
* Points the player and the download link at a result, or clears them.
*
* @remarks
* The recorder revokes the URL of a result on the next `start()`, on `discard()` and on `destroy()`, so the player
* is cleared before any of them: its `src` is removed and `load()` drops the media.
*/
export function showResult(root: HTMLElement, result: MediaRecordingResult | null): void {
const player = root.querySelector<HTMLAudioElement>('[data-player]')!;
const link = root.querySelector<HTMLAnchorElement>('[data-download]')!;
if (result) {
player.src = result.url;
link.href = result.url;
link.download = `voice-memo.${extensionOf(result.mimeType)}`;
return;
}
player.removeAttribute('src');
player.load();
link.removeAttribute('href');
}<div data-controller="voice-memo" data-state="idle">
<div data-meter aria-hidden="true"><span></span></div>
<output data-elapsed>0:00</output>
<div data-controls>
<button
type="button"
class="rui-button rui-button--filled rui-button--lg rui-button--square"
data-record
aria-label="Record"
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<circle cx="12" cy="12" r="6" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-pause
aria-label="Pause"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="pause">
<path d="M7 5h3v14H7zM14 5h3v14h-3z" fill="currentColor" />
</svg>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="resume">
<path d="M8 5v14l10-7z" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-stop
aria-label="Stop"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<path d="M7 7h10v10H7z" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-discard
aria-label="Discard"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<path
d="M5 7h14M10 7V5h4v2M7 7l1 12h8l1-12"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
</div>
<div data-result hidden>
<audio data-player controls preload="auto"></audio>
<a class="rui-button rui-button--outline rui-button--sm" data-download download="voice-memo.webm">Download</a>
</div>
<p data-status aria-live="polite">Press Record to start. It stops by itself after 1:00.</p>
</div>.primitive-example:is(
[data-example='voice-memo'],
:has(> voice-memo-element, > [data-controller='voice-memo'], > voice-memo-app)
) {
display: flex;
flex-direction: column;
align-items: stretch;
gap: var(--space-stack);
box-sizing: border-box;
width: min(100%, 24rem);
padding: var(--space-inset);
border: 1px solid var(--border);
border-radius: var(--radius-container);
background: var(--surface);
color: var(--on-surface);
box-shadow: var(--shadow-overlay);
--voice-memo-muted: color-mix(in srgb, currentColor 78%, var(--surface));
& :where(voice-memo-element, [data-controller='voice-memo'], voice-memo-app) {
display: flex;
flex-direction: column;
gap: var(--space-stack);
min-width: 0;
}
& :where([data-meter]) {
position: relative;
height: 0.5rem;
overflow: hidden;
border-radius: var(--radius-full);
background: var(--surface-container-high);
& > span {
position: absolute;
inset: 0;
transform: scaleX(var(--level, 0));
transform-origin: left center;
border-radius: inherit;
background: var(--primary);
transition: transform 90ms linear;
}
}
& :where([data-meter]:not([data-state='recording']) > span) {
opacity: 0.4;
}
& :where([data-elapsed]) {
font-size: 2rem;
line-height: 1;
font-variant-numeric: tabular-nums;
}
& :where([data-controls]) {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
}
& [data-pause] [data-icon='resume'],
& [data-pause][data-paused] [data-icon='pause'] {
display: none;
}
& [data-pause][data-paused] [data-icon='resume'] {
display: block;
}
& :where([data-result]) {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
& > audio {
flex: 1 1 12rem;
min-width: 0;
width: 100%;
}
}
& :where([data-result][hidden]) {
display: none;
}
& :where([data-status]) {
margin: 0;
font-size: 0.8125rem;
color: var(--voice-memo-muted);
}
& :where([data-status]:is([data-state='denied'], [data-state='error'], [data-state='unsupported'])) {
color: var(--error);
font-weight: 500;
}
}The element form's logic on a controller, with connect() in place of onConnected(). There is no tag to define, so the markup can come from a server template or a CMS and be any element; the registry attaches the class through data-controller and createMediaRecorderController(this, ...) takes the controller as its host.
A mount function builds the recorder over the markup and returns the cleanup that undoes it.
import { MediaRecorderController } from '@ecopages/radiant-ui/controllers';
import { MeterContext, createRecorderConfig, paint, showResult, viewOf } from './voice-memo.data';
export function mount(root: HTMLElement): () => void {
const part = <T extends HTMLElement>(selector: string) => root.querySelector<T>(selector)!;
const meter = new MeterContext();
const listeners = new AbortController();
const { signal } = listeners;
const recorder = new MediaRecorderController(
createRecorderConfig(meter, {
onState: (snapshot) => paint(root, viewOf(snapshot)),
onStop: (result) => showResult(root, result),
}),
);
const clearResult = () => showResult(root, null);
part('[data-record]').addEventListener(
'click',
() => {
clearResult();
void recorder.start();
},
{ signal },
);
part('[data-pause]').addEventListener(
'click',
() => (recorder.getState().status === 'paused' ? recorder.resume() : recorder.pause()),
{ signal },
);
part('[data-stop]').addEventListener('click', () => void recorder.stop(), { signal });
part('[data-discard]').addEventListener(
'click',
() => {
clearResult();
recorder.discard();
},
{ signal },
);
recorder.attach();
paint(root, viewOf(recorder.getState()));
return () => {
listeners.abort();
clearResult();
recorder.destroy();
meter.close();
paint(root, viewOf(recorder.getState()));
};
}import { formatMediaTime } from '@ecopages/radiant-ui/helpers';
import type {
MediaRecorderControllerConfig,
MediaRecorderSnapshot,
MediaRecorderStatus,
MediaRecordingResult,
} from '@ecopages/radiant-ui/controllers';
/** Seconds after which the recorder stops by itself. */
export const MAX_DURATION = 60;
export const MIME_TYPES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg;codecs=opus'];
const LIMIT_TEXT = formatMediaTime(MAX_DURATION);
/** What a form draws for one recorder snapshot, so every form shows the same thing. */
export type VoiceMemoView = {
state: MediaRecorderStatus;
status: string;
elapsed: string;
/** Loudness from 0 to 1. */
level: number;
record: boolean;
pause: boolean;
stop: boolean;
discard: boolean;
/** The recording is paused, so the pause button resumes. */
paused: boolean;
/** There is a recording to play and download. */
result: boolean;
};
function statusText(snapshot: MediaRecorderSnapshot): string {
switch (snapshot.status) {
case 'idle':
return `Press Record to start. It stops by itself after ${LIMIT_TEXT}.`;
case 'requesting':
return 'Waiting for permission to use the microphone.';
case 'recording':
return `Recording. It stops by itself at ${LIMIT_TEXT}.`;
case 'paused':
return 'Paused. Press Resume to go on, or Stop to finish.';
case 'stopped':
return snapshot.duration >= MAX_DURATION - 0.5
? `Stopped at the ${LIMIT_TEXT} limit. Play it back, download it or discard it.`
: `Recorded ${formatMediaTime(snapshot.duration)}. Play it back, download it or discard it.`;
case 'denied':
return 'Microphone access is blocked. Allow the microphone for this site in the browser settings, then press Record to try again.';
case 'unsupported':
return 'This browser cannot record audio.';
case 'error':
return 'Recording failed. Press Record to try again.';
}
}
/** Maps a recorder snapshot to what the controls, the clock, the meter and the status line show. */
export function viewOf(snapshot: MediaRecorderSnapshot): VoiceMemoView {
const { status } = snapshot;
const live = status === 'recording' || status === 'paused';
return {
state: status,
status: statusText(snapshot),
elapsed: formatMediaTime(snapshot.duration),
level: snapshot.level,
record: status === 'idle' || status === 'stopped' || status === 'denied' || status === 'error',
pause: live,
stop: live,
discard: live || status === 'stopped',
paused: status === 'paused',
result: status === 'stopped',
};
}
function extensionOf(mimeType: string): string {
const subtype = mimeType.split(';')[0].split('/')[1] ?? 'webm';
return subtype === 'mp4' ? 'm4a' : subtype;
}
/**
* The recorder's settings, shared by every form.
*
* @remarks
* The level meter needs an `AudioContext`. `getAudioContext` runs inside `start()`, which a click calls, so the
* context is created and resumed inside that gesture. The recorder only reads the stream into an analyser and never
* connects it to the speakers.
*/
export function createRecorderConfig(
context: MeterContext,
config: Pick<MediaRecorderControllerConfig, 'onState' | 'onStop'>,
): MediaRecorderControllerConfig {
return {
mimeTypes: MIME_TYPES,
maxDuration: MAX_DURATION,
timeslice: 250,
getAudioContext: () => context.get(),
...config,
};
}
/** One `AudioContext` for the life of a memo, created on first use and closed with it. */
export class MeterContext {
private context: AudioContext | null = null;
get(): AudioContext {
this.context ??= new AudioContext();
void this.context.resume();
return this.context;
}
close(): void {
void this.context?.close();
this.context = null;
}
}
/**
* Draws a view into the markup of a plain, element or controller form: `data-state` on the root, the status line and
* the meter (the stylesheet selects on the ones it styles), the clock and the four buttons.
*/
export function paint(root: HTMLElement, view: VoiceMemoView): void {
const part = <T extends HTMLElement>(selector: string) => root.querySelector<T>(selector)!;
root.dataset.state = view.state;
part('[data-status]').textContent = view.status;
part('[data-status]').dataset.state = view.state;
part('[data-elapsed]').textContent = view.elapsed;
part('[data-meter]').dataset.state = view.state;
part('[data-meter]').style.setProperty('--level', view.level.toFixed(2));
part<HTMLButtonElement>('[data-record]').disabled = !view.record;
part<HTMLButtonElement>('[data-stop]').disabled = !view.stop;
part<HTMLButtonElement>('[data-discard]').disabled = !view.discard;
const pause = part<HTMLButtonElement>('[data-pause]');
pause.disabled = !view.pause;
pause.setAttribute('aria-label', view.paused ? 'Resume' : 'Pause');
pause.toggleAttribute('data-paused', view.paused);
part('[data-result]').hidden = !view.result;
}
/**
* Points the player and the download link at a result, or clears them.
*
* @remarks
* The recorder revokes the URL of a result on the next `start()`, on `discard()` and on `destroy()`, so the player
* is cleared before any of them: its `src` is removed and `load()` drops the media.
*/
export function showResult(root: HTMLElement, result: MediaRecordingResult | null): void {
const player = root.querySelector<HTMLAudioElement>('[data-player]')!;
const link = root.querySelector<HTMLAnchorElement>('[data-download]')!;
if (result) {
player.src = result.url;
link.href = result.url;
link.download = `voice-memo.${extensionOf(result.mimeType)}`;
return;
}
player.removeAttribute('src');
player.load();
link.removeAttribute('href');
}<div data-example="voice-memo" data-state="idle">
<div data-meter aria-hidden="true"><span></span></div>
<output data-elapsed>0:00</output>
<div data-controls>
<button
type="button"
class="rui-button rui-button--filled rui-button--lg rui-button--square"
data-record
aria-label="Record"
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<circle cx="12" cy="12" r="6" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-pause
aria-label="Pause"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="pause">
<path d="M7 5h3v14H7zM14 5h3v14h-3z" fill="currentColor" />
</svg>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false" data-icon="resume">
<path d="M8 5v14l10-7z" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-stop
aria-label="Stop"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<path d="M7 7h10v10H7z" fill="currentColor" />
</svg>
</button>
<button
type="button"
class="rui-button rui-button--ghost rui-button--md rui-button--square"
data-discard
aria-label="Discard"
disabled
>
<svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false">
<path
d="M5 7h14M10 7V5h4v2M7 7l1 12h8l1-12"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</button>
</div>
<div data-result hidden>
<audio data-player controls preload="auto"></audio>
<a class="rui-button rui-button--outline rui-button--sm" data-download download="voice-memo.webm">Download</a>
</div>
<p data-status aria-live="polite">Press Record to start. It stops by itself after 1:00.</p>
</div>.primitive-example:is(
[data-example='voice-memo'],
:has(> voice-memo-element, > [data-controller='voice-memo'], > voice-memo-app)
) {
display: flex;
flex-direction: column;
align-items: stretch;
gap: var(--space-stack);
box-sizing: border-box;
width: min(100%, 24rem);
padding: var(--space-inset);
border: 1px solid var(--border);
border-radius: var(--radius-container);
background: var(--surface);
color: var(--on-surface);
box-shadow: var(--shadow-overlay);
--voice-memo-muted: color-mix(in srgb, currentColor 78%, var(--surface));
& :where(voice-memo-element, [data-controller='voice-memo'], voice-memo-app) {
display: flex;
flex-direction: column;
gap: var(--space-stack);
min-width: 0;
}
& :where([data-meter]) {
position: relative;
height: 0.5rem;
overflow: hidden;
border-radius: var(--radius-full);
background: var(--surface-container-high);
& > span {
position: absolute;
inset: 0;
transform: scaleX(var(--level, 0));
transform-origin: left center;
border-radius: inherit;
background: var(--primary);
transition: transform 90ms linear;
}
}
& :where([data-meter]:not([data-state='recording']) > span) {
opacity: 0.4;
}
& :where([data-elapsed]) {
font-size: 2rem;
line-height: 1;
font-variant-numeric: tabular-nums;
}
& :where([data-controls]) {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
}
& [data-pause] [data-icon='resume'],
& [data-pause][data-paused] [data-icon='pause'] {
display: none;
}
& [data-pause][data-paused] [data-icon='resume'] {
display: block;
}
& :where([data-result]) {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
& > audio {
flex: 1 1 12rem;
min-width: 0;
width: 100%;
}
}
& :where([data-result][hidden]) {
display: none;
}
& :where([data-status]) {
margin: 0;
font-size: 0.8125rem;
color: var(--voice-memo-muted);
}
& :where([data-status]:is([data-state='denied'], [data-state='error'], [data-state='unsupported'])) {
color: var(--error);
font-weight: 500;
}
}mount runs once for each example element on the page, and the function it returns undoes it; see how the examples run. The cleanup removes the listeners, clears the player, destroys the recorder, which stops the microphone, and closes the audio context.
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.