v22.18.0 release notes

SpeechToTextButton

SpeechToTextButton dictates text into an input, a textarea, a Chat composer or a model, with the interim words replaced as the user speaks. It uses the speech recognition of the browser, with no service, key or dependency, accepts your own engine, and is disabled with an explanation where the browser cannot recognize speech.

View as .md
import { SpeechToText, SpeechToTextButton } from '@exhaustive-ui/core/speechtotextbutton';

The same entry point exports the SpeechToText directive, that marks the field the button writes into, the SPEECH_TO_TEXT_PROVIDER token and WebSpeechToTextProvider, the default engine, to bring your own speech recognition.

SpeechToTextButton starts a dictation when it is pressed and stops it when it is pressed again, with Escape, or after a pause. What the user says is appended to transcript, a model to bind two-way. It uses the speech recognition of the browser, the Web Speech API: no service to set up, no key and no dependency. The browser asks for the microphone the first time.

Where the speech is recognized depends on the browser: Chrome and Edge send the audio to the speech service of their vendor, Safari may recognize it on the device. Tell your users when that matters, or bring your own engine with a custom provider.

Press the button and say something.

for writes the dictation into an input or a textarea, at the caret it had when it lost the focus, or at the end: put pSpeechToText on the field and pass its reference. The text is written as the user speaks and corrected when the phrase is final, and an input event is dispatched on each change, so ngModel, reactive forms and Signal Forms see it. While the dictation runs, Escape in the field stops it and the field has a data-p-dictating attribute. for also takes a plain element, an ElementRef or a CSS selector.

While the user speaks, the engine gives interim results, a guess that changes, then a final result for each phrase. onResult emits both, with transcript, isFinal and up to maxAlternativesalternatives with their confidence: each interim result replaces the previous one, a final result is given once. Here the final text is black and the interim one gray. Set interimResults to false to only receive final results. continuous keeps listening after a pause, until the button is pressed again.

onStart, onEnd with the final transcript and the reason, and onError with a readable message complete the events.

lang is the language of the speech, a BCP 47 tag such as en-US, fr-FR or ja-JP. It defaults to the lang attribute of the document, then to the language of the browser, so a localized application usually has nothing to set. The labels of the button are translated separately, see Labels.

Language of the speechEnglishFrançaisDeutschEspañol

In a Chat, put the button in the composerActions template, next to the attach button, and bind the same signal to the draft of the Chat and to the transcript of the button: the words appear in the composer as they are said, the interim ones replaced, and the user can correct them before sending. disabled comes from the template context, so the button follows the Chat.

Assistant

Press the microphone and dictate your message, then send it.

SpeechToTextButton is a Button: severity, variant (text or outlined), size, rounded and raised work the same way. It is secondary by default and turns danger while listening, with a stop icon and a pulsing ring; listeningSeverity changes that color, null keeps the severity. iconOnly hides the text, which stays the accessible name; add tooltip to show it on hover and focus.

Chrome, Edge and Safari implement the speech recognition of the Web Speech API; Firefox does not, and neither do some embedded browsers. There, and on the server, the button is disabled, its accessible name says why and a tooltip explains it on hover. isSupported, a signal of the component, lets you hide it instead, or show another way to enter the text. This demo simulates a browser without speech recognition.

The browser also needs a secure context, HTTPS or localhost, and the permission to use the microphone: a refusal emits onError with not-allowed and is announced.

Dictation is not available here: type your message instead.

The engine is pluggable. A SpeechToTextProvider has two methods: isSupported(), and start(options), that returns a session with a results observable, stop() and abort(). Emit interim results as often as you like, each one replacing the previous, then each final result once; complete when the engine stops listening, and error with a code such as network or not-allowed. Give it to one button with provider, or to the whole application with the SPEECH_TO_TEXT_PROVIDER token.

This lets you record with getUserMedia and MediaRecorder and send the audio to your own server, or run a speech model in the browser, for languages or browsers that the Web Speech API does not cover, or to keep the audio away from third parties. ExhaustiveUI ships no such engine and needs no account. The demo below uses a pretend engine that types a fixed sentence, so it works everywhere.

import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { SPEECH_TO_TEXT_PROVIDER, SpeechToTextOptions, SpeechToTextProvider, SpeechToTextResult, SpeechToTextSession } from '@exhaustive-ui/core/speechtotextbutton';
import { Observable } from 'rxjs';

/** Records the microphone and sends the audio to your own transcription endpoint when the user stops. */
@Injectable({ providedIn: 'root' })
export class ServerSpeechProvider implements SpeechToTextProvider {
    private http = inject(HttpClient);

    isSupported() {
        return typeof MediaRecorder !== 'undefined' && !!navigator.mediaDevices?.getUserMedia;
    }

    start(options: SpeechToTextOptions): SpeechToTextSession {
        let recorder: MediaRecorder | undefined;
        let cancelled = false;
        const results = new Observable<SpeechToTextResult>((subscriber) => {
            const chunks: Blob[] = [];
            navigator.mediaDevices.getUserMedia({ audio: true }).then(
                (stream) => {
                    recorder = new MediaRecorder(stream);
                    recorder.ondataavailable = (event) => chunks.push(event.data);
                    recorder.onstop = () => {
                        stream.getTracks().forEach((track) => track.stop());
                        if (cancelled) return subscriber.complete();
                        const body = new FormData();
                        body.append('audio', new Blob(chunks, { type: recorder!.mimeType }));
                        body.append('lang', options.lang);
                        this.http.post<{ text: string }>('/api/transcribe', body).subscribe({
                            next: ({ text }) => {
                                subscriber.next({ transcript: text, isFinal: true, alternatives: [{ transcript: text, confidence: 1 }] });
                                subscriber.complete();
                            },
                            error: () => subscriber.error({ error: 'network' })
                        });
                    };
                    recorder.start();
                },
                () => subscriber.error({ error: 'not-allowed' })
            );
            return () => recorder?.state === 'recording' && recorder.stop();
        });
        return {
            results,
            stop: () => recorder?.stop(),
            abort: () => {
                cancelled = true;
                recorder?.stop();
            }
        };
    }
}

// for the whole application
providers: [{ provide: SPEECH_TO_TEXT_PROVIDER, useExisting: ServerSpeechProvider }]

The texts of the button, start and stop, the unsupported reason, the listening and stopped announcements and the error messages (notAllowed, noSpeech, network, audioCapture, languageNotSupported, unknown) are translated for one button with labels. For the whole application, the startDictation, stopDictation, dictationUnsupported, dictationStarted and dictationStopped keys of the aria translation set the first five. Missing keys keep their English default.

provideExhaustive({
    translation: {
        aria: {
            startDictation: 'Dicter',
            stopDictation: 'Arrêter la dictée',
            dictationUnsupported: "La dictée n'est pas prise en charge par ce navigateur",
            dictationStarted: 'Écoute en cours',
            dictationStopped: 'Dictée arrêtée'
        }
    }
});

Screen Reader

SpeechToTextButton is a native button that works as a toggle: aria-pressed is true while it listens. Its visible text, "Start dictation" then "Stop dictation", is its accessible name; with iconOnly, the same text becomes its aria-label. ariaLabel gives a more precise name while idle, such as "Dictate the message"; when the text is visible, it has to contain it, so that voice control users can say what they see. The icons are hidden from assistive technologies.

A polite live region announces "Listening" when the dictation starts, "Dictation stopped" when it ends and a readable message on an error, such as "Microphone access was denied", without moving the focus. Announcing the text itself is left to the field it is written into. When speech recognition is not supported, the button is disabled and its accessible name ends with the reason. The texts are translated with labels or the aria translation.

The pulsing ring around the button while listening is not the only sign of the state, which the stop icon, the text and aria-pressed also give; when the user prefers reduced motion, the ring stays still. The error icon of text and outlined buttons has a 3:1 contrast or more in both color schemes.

<p-speech-to-text-button [iconOnly]="true" ariaLabel="Dictate the message" [tooltip]="true" />

<label for="notes">Notes</label>
<textarea id="notes" pSpeechToText #notes="pSpeechToText"></textarea>
<p-speech-to-text-button [for]="notes" />

Keyboard Support

The button is in the tab order and keeps the focus during the dictation.

KeyFunction
tabMoves focus to the button.
enter / spaceStarts the dictation, or stops it while listening.
escapeStops the dictation, on the button or in the field that has the pSpeechToText directive. When idle, it hides the tooltip.