# Angular SpeechToTextButton Component

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.

## Basic

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 .

```typescript
import { Component, signal } from '@angular/core';
import { SpeechToTextButtonModule } from '@exhaustive-ui/core/speechtotextbutton';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-4">
            <p-speech-to-text-button [(transcript)]="text" />
            <p class="m-0 min-h-6 max-w-[32rem] text-center" aria-live="off">{{ text() || 'Press the button and say something.' }}</p>
        </div>
    `,
    standalone: true,
    imports: [SpeechToTextButtonModule]
})
export class SpeechtotextbuttonBasicDemo {
    text = signal('');
}
```

## Fill an Input

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.

```typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { InputGroupModule } from '@exhaustive-ui/core/inputgroup';
import { InputGroupAddonModule } from '@exhaustive-ui/core/inputgroupaddon';
import { InputTextModule } from '@exhaustive-ui/core/inputtext';
import { SpeechToTextButtonModule } from '@exhaustive-ui/core/speechtotextbutton';
import { TextareaModule } from '@exhaustive-ui/core/textarea';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-6">
            <div class="flex flex-col gap-2 w-full max-w-[28rem]">
                <label for="stt-target-search">Search</label>
                <p-input-group>
                    <input id="stt-target-search" pInputText pSpeechToText #search="pSpeechToText" [(ngModel)]="query" />
                    <p-input-group-addon>
                        <p-speech-to-text-button [for]="search" [iconOnly]="true" variant="text" [rounded]="true" ariaLabel="Start dictation in the search" [tooltip]="true" />
                    </p-input-group-addon>
                </p-input-group>
            </div>
            <div class="flex flex-col gap-2 w-full max-w-[28rem]">
                <label for="stt-target-notes">Notes</label>
                <textarea id="stt-target-notes" pTextarea pSpeechToText #notes="pSpeechToText" rows="4" class="w-full" [(ngModel)]="text"></textarea>
                <div class="flex justify-end">
                    <p-speech-to-text-button [for]="notes" [continuous]="true" size="small" />
                </div>
            </div>
        </div>
    `,
    standalone: true,
    imports: [SpeechToTextButtonModule, InputGroupModule, InputGroupAddonModule, InputTextModule, TextareaModule, FormsModule]
})
export class SpeechtotextbuttonTargetDemo {
    query = '';

    text = 'Meeting notes: ';
}
```

## Interim Results and Events

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 maxAlternatives alternatives 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.

```typescript
import { Component, signal } from '@angular/core';
import { SpeechToTextButtonModule, SpeechToTextErrorEvent, SpeechToTextResult } from '@exhaustive-ui/core/speechtotextbutton';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-4">
            <p-speech-to-text-button [continuous]="true" [maxAlternatives]="3" (onStart)="log('start')" (onResult)="onResult($event)" (onEnd)="log('end: ' + $event.reason)" (onError)="onError($event)" />
            <p class="m-0 min-h-6 max-w-[32rem] text-center">
                <span>{{ finalText() }}</span>
                @if (interim()) {
                    <span class="text-muted-color italic"> {{ interim() }}</span>
                }
            </p>
            <ul class="m-0 p-0 list-none text-sm text-muted-color text-center">
                @for (entry of events(); track $index) {
                    <li>{{ entry }}</li>
                }
            </ul>
        </div>
    `,
    standalone: true,
    imports: [SpeechToTextButtonModule]
})
export class SpeechtotextbuttonInterimDemo {
    finalText = signal('');

    interim = signal('');

    events = signal<string[]>([]);

    onResult(result: SpeechToTextResult) {
        if (result.isFinal) {
            this.finalText.update((text) => (text + ' ' + result.transcript).trim());
            this.interim.set('');
            this.log(`final: "${result.transcript.trim()}" (${result.alternatives.length} alternatives)`);
        } else {
            this.interim.set(result.transcript);
        }
    }

    onError(event: SpeechToTextErrorEvent) {
        this.log(`error: ${event.error}, ${event.message}`);
    }

    log(entry: string) {
        this.events.update((events) => [entry, ...events].slice(0, 5));
    }
}
```

## Language

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 .

```typescript
import { Component, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SelectButtonModule } from '@exhaustive-ui/core/selectbutton';
import { SpeechToTextButtonModule } from '@exhaustive-ui/core/speechtotextbutton';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-4">
            <span id="stt-language-label" class="font-medium">Language of the speech</span>
            <p-select-button [options]="languages" optionLabel="label" optionValue="value" [(ngModel)]="lang" [allowEmpty]="false" ariaLabelledBy="stt-language-label" />
            <p-speech-to-text-button [lang]="lang" [(transcript)]="text" />
            <p class="m-0 min-h-6 max-w-[32rem] text-center" [attr.lang]="lang">{{ text() }}</p>
        </div>
    `,
    standalone: true,
    imports: [SpeechToTextButtonModule, SelectButtonModule, FormsModule]
})
export class SpeechtotextbuttonLanguageDemo {
    languages = [
        { label: 'English', value: 'en-US' },
        { label: 'Français', value: 'fr-FR' },
        { label: 'Deutsch', value: 'de-DE' },
        { label: 'Español', value: 'es-ES' }
    ];

    lang = 'en-US';

    text = signal('');
}
```

## Chat Composer

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.

```typescript
import { Component, signal } from '@angular/core';
import { ChatMessage, ChatModule, ChatSendEvent } from '@exhaustive-ui/core/chat';
import { SpeechToTextButtonModule } from '@exhaustive-ui/core/speechtotextbutton';

@Component({
    template: `
        <div class="card">
            <p-chat class="h-[24rem]" [messages]="messages()" [(draft)]="draft" placeholder="Type or dictate a message" (send)="onSend($event)">
                <ng-template #composerActions let-disabled="disabled">
                    <p-speech-to-text-button [(transcript)]="draft" [disabled]="disabled" [iconOnly]="true" variant="text" [rounded]="true" size="small" ariaLabel="Dictate a message" [tooltip]="true" />
                </ng-template>
            </p-chat>
        </div>
    `,
    standalone: true,
    imports: [ChatModule, SpeechToTextButtonModule]
})
export class SpeechtotextbuttonChatDemo {
    draft = signal('');

    messages = signal<ChatMessage[]>([{ id: 1, role: 'assistant', content: 'Press the microphone and dictate your message, then send it.' }]);

    private nextId = 2;

    onSend({ text }: ChatSendEvent) {
        this.messages.update((messages) => [...messages, { id: this.nextId++, role: 'user', content: text }, { id: this.nextId++, role: 'assistant', content: `You said: *${text}*` }]);
    }
}
```

## Button Styles

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.

```typescript
import { Component } from '@angular/core';
import { SpeechToTextButtonModule } from '@exhaustive-ui/core/speechtotextbutton';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-6">
            <div class="flex flex-wrap items-center justify-center gap-3">
                <p-speech-to-text-button [iconOnly]="true" [rounded]="true" [tooltip]="true" />
                <p-speech-to-text-button [iconOnly]="true" variant="text" [rounded]="true" [tooltip]="true" />
                <p-speech-to-text-button [iconOnly]="true" variant="outlined" [tooltip]="true" />
                <p-speech-to-text-button severity="primary" listeningSeverity="contrast" />
                <p-speech-to-text-button variant="outlined" [rounded]="true" />
            </div>
            <div class="flex flex-wrap items-center justify-center gap-3">
                <p-speech-to-text-button size="small" [iconOnly]="true" [rounded]="true" />
                <p-speech-to-text-button [iconOnly]="true" [rounded]="true" />
                <p-speech-to-text-button size="large" [iconOnly]="true" [rounded]="true" [raised]="true" />
            </div>
        </div>
    `,
    standalone: true,
    imports: [SpeechToTextButtonModule]
})
export class SpeechtotextbuttonStylesDemo {
}
```

## Unsupported Browsers

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.

```typescript
import { Component } from '@angular/core';
import { SpeechToTextButtonModule, SpeechToTextProvider } from '@exhaustive-ui/core/speechtotextbutton';
import { EMPTY } from 'rxjs';

@Component({
    template: `
        <div class="card flex flex-wrap items-center justify-center gap-4">
            <p-speech-to-text-button [provider]="unsupported" />
            <p-speech-to-text-button [provider]="unsupported" [iconOnly]="true" [rounded]="true" />
            <p-speech-to-text-button #dictation [provider]="unsupported" [iconOnly]="true" variant="outlined" />
            @if (!dictation.isSupported()) {
                <span class="text-sm text-muted-color">Dictation is not available here: type your message instead.</span>
            }
        </div>
    `,
    standalone: true,
    imports: [SpeechToTextButtonModule]
})
export class SpeechtotextbuttonUnsupportedDemo {
    // a provider that is never supported, as the browser engine in Firefox
    unsupported: SpeechToTextProvider = {
        isSupported: () => false,
        start: () => ({ results: EMPTY, stop: () => {}, abort: () => {} })
    };
}
```

## Custom Provider

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.

```typescript
import { Component, signal } from '@angular/core';
import { SpeechToTextButtonModule, SpeechToTextOptions, SpeechToTextProvider, SpeechToTextResult, SpeechToTextSession } from '@exhaustive-ui/core/speechtotextbutton';
import { Observable } from 'rxjs';

/** A pretend engine that "hears" a fixed sentence, word by word, so the demo works in every browser without a microphone. */
class ScriptedSpeechProvider implements SpeechToTextProvider {
    isSupported() {
        return true;
    }

    start(options: SpeechToTextOptions): SpeechToTextSession {
        const words = 'The quick brown fox jumps over the lazy dog'.split(' ');
        let stopped = false;
        let stop = () => {};
        const results = new Observable<SpeechToTextResult>((subscriber) => {
            let count = 0;
            const timer = setInterval(() => {
                count++;
                const transcript = words.slice(0, count).join(' ');
                const isFinal = count === words.length || stopped;
                if (options.interimResults || isFinal) {
                    subscriber.next({ transcript, isFinal, alternatives: [{ transcript, confidence: isFinal ? 0.95 : 0.6 }] });
                }
                if (isFinal) {
                    clearInterval(timer);
                    subscriber.complete();
                }
            }, 250);
            stop = () => (stopped = true);
            return () => clearInterval(timer);
        });
        return { results, stop: () => stop(), abort: () => stop() };
    }
}

@Component({
    template: `
        <div class="card flex flex-col items-center gap-4">
            <p-speech-to-text-button [provider]="scripted" [(transcript)]="text" severity="primary" />
            <p class="m-0 min-h-6 max-w-[32rem] text-center">{{ text() }}</p>
        </div>
    `,
    standalone: true,
    imports: [SpeechToTextButtonModule]
})
export class SpeechtotextbuttonProviderDemo {
    scripted = new ScriptedSpeechProvider();

    text = signal('');
}
```

## Labels

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.

```typescript
import { Component } from '@angular/core';
import { SpeechToTextButtonModule } from '@exhaustive-ui/core/speechtotextbutton';

@Component({
    template: `
        <div class="card flex flex-wrap items-center justify-center gap-3">
            <p-speech-to-text-button lang="fr-FR" [labels]="{ start: 'Dicter', stop: 'Arrêter la dictée', listening: 'Écoute en cours', stopped: 'Dictée arrêtée', noSpeech: 'Aucune parole détectée' }" />
            <p-speech-to-text-button lang="de-DE" [labels]="{ start: 'Diktieren', stop: 'Diktat beenden', listening: 'Hört zu', stopped: 'Diktat beendet' }" />
        </div>
    `,
    standalone: true,
    imports: [SpeechToTextButtonModule]
})
export class SpeechtotextbuttonLabelsDemo {
}
```

## Accessibility

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.

## Speech To Text Button

SpeechToTextButton dictates text with the speech recognition of the browser, the Web Speech API, or with your own engine: it writes the transcript into an input or a textarea, with the interim text replaced as the user speaks, or into a two-way bound transcript. It needs no service, key or dependency; in browsers without speech recognition, such as Firefox, it is disabled and says why.

### Props

| Name | Type | Default | Description |
|------|------|---------|-------------|
| dt | Object | undefined | Defines scoped design tokens of the component. |
| unstyled | boolean | undefined | Indicates whether the component should be rendered without styles. |
| pt | any | undefined | Used to pass attributes to DOM elements inside the component. |
| ptOptions | PassThroughOptions | undefined | Used to configure passthrough(pt) options of the component. |
| lang | string | - | Language of the speech, a BCP 47 tag such as  `en-US`  or  `fr-FR` . Defaults to the lang attribute of the document, then to the language of the browser. |
| continuous | boolean | false | Whether the dictation goes on after a pause, until the button is pressed again. Otherwise it ends after the first phrase. |
| interimResults | boolean | true | Whether the text is written while the user speaks, then corrected when the phrase is final. |
| maxAlternatives | number | 1 | Maximum number of alternatives given in each result. |
| provider | SpeechToTextProvider | - | Speech recognition engine of this button. Defaults to the SPEECH_TO_TEXT_PROVIDER token, the Web Speech API of the browser. |
| for | SpeechToTextTarget | - | Input or textarea that receives the transcript, at its caret: a template reference, an ElementRef, a CSS selector or an element with the pSpeechToText directive. An input event is dispatched on each change, so that forms see it. |
| transcript | string | '' | Text dictated, appended to its value when a dictation starts. Bind it two-way with [(transcript)]. |
| errorDuration | number | 3000 | Duration of the error state, in milliseconds. |
| iconOnly | boolean | false | Whether the button only shows the icon. Its text is then its accessible name. |
| tooltip | boolean | false | Whether a tooltip shows the text of the button on hover and focus, useful with iconOnly. A tooltip always explains why the button is disabled when speech recognition is not supported. |
| tooltipPosition | "top" \| "bottom" \| "left" \| "right" | 'top' | Position of the tooltip. |
| severity | ButtonSeverity | 'secondary' | Defines the style of the button, as in Button. |
| listeningSeverity | ButtonSeverity | 'danger' | Style of the button while listening. null keeps the severity. |
| variant | "text" \| "outlined" | - | Specifies the variant of the button, as in Button. |
| size | "small" \| "large" | - | Defines the size of the button. |
| rounded | boolean | false | Add a circular border radius to the button. |
| raised | boolean | false | Add a shadow to indicate elevation. |
| disabled | boolean | false | When present, it specifies that the button should be disabled. A dictation in progress is stopped. |
| tabindex | number | - | Index of the button in the tab order. |
| autofocus | boolean | false | When present, it specifies that the button should automatically get focus on load. |
| ariaLabel | string | - | Accessible name of the button while idle, such as "Dictate the message". With a visible text, it has to contain that text. |
| announce | boolean | true | Whether the start, the end and the errors are announced to screen readers through a polite live region. |
| labels | Partial<SpeechToTextButtonLabels> | - | Texts of the component, merged with the translation and the defaults. |

### Emits

| Name | Parameters | Description |
|------|------------|-------------|
| onStart | event: SpeechToTextStartEvent | Callback to invoke when the dictation starts. |
| onEnd | event: SpeechToTextEndEvent | Callback to invoke when the dictation ends, after the last result. |
| onResult | value: SpeechToTextResult | Callback to invoke on each result: interim ones while the user speaks, then the final one. |
| onError | event: SpeechToTextErrorEvent | Callback to invoke when the dictation fails: microphone refused, nothing heard, network, no microphone... |

### Templates

| Name | Type | Description |
|------|------|-------------|
| icon | TemplateRef<SpeechToTextButtonIconTemplateContext> | Custom icon template. |

### Methods

| Name | Parameters | Return Type | Description |
|------|------------|-------------|-------------|
| toggle | event: Event | void | Starts the dictation, or stops it while listening. Called by a click on the button. |
| start | event: Event | void | Starts the dictation. |
| stop |  | void | Stops listening; what was already said is still written. |
| abort |  | void | Stops listening right away and drops the text that is not final yet. |

## Pass Through Options

| Name | Type | Description |
|------|------|-------------|
| host | PassThroughOption<HTMLElement, I> | Used to pass attributes to the host's DOM element. |
| root | PassThroughOption<HTMLElement, I> | Used to pass attributes to the root's DOM element, the host. |
| pcButton | ButtonPassThrough | Used to pass attributes to the Button component. |
| tooltipTarget | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the element that holds the button and the tooltip, when a tooltip is shown. |
| tooltip | TooltipPassThrough | Used to pass attributes to the Tooltip directive. |
| icon | PassThroughOption<SVGElement, I> | Used to pass attributes to the microphone, stop or error icon. |
| liveRegion | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the live region that announces the start, the end and the errors. |

## Theming

### CSS Classes

| Class | Description |
|-------|-------------|
| p-speechtotextbutton | Class name of the root element |
| p-speechtotextbutton-listening | Class name of the root element while listening |
| p-speechtotextbutton-error | Class name of the root element after an error |
| p-speechtotextbutton-unsupported | Class name of the root element when speech recognition is not supported |
| p-speechtotextbutton-tooltip-target | Class name of the element that holds the button when a tooltip is shown |
| p-speechtotextbutton-button | Class name of the button element |
| p-speechtotextbutton-icon | Class name of the icon element |

### Design Tokens

| Token | CSS Variable | Description |
|-------|--------------|-------------|
| speechtotextbutton.transition.duration | --p-speechtotextbutton-transition-duration | Transition duration of root |
| speechtotextbutton.icon.size | --p-speechtotextbutton-icon-size | Size of icon |
| speechtotextbutton.icon.sm.size | --p-speechtotextbutton-icon-sm-size | Size of icon in a small button |
| speechtotextbutton.icon.lg.size | --p-speechtotextbutton-icon-lg-size | Size of icon in a large button |
| speechtotextbutton.icon.error.color | --p-speechtotextbutton-icon-error-color | Error color of icon, in text and outlined buttons |
| speechtotextbutton.pulse.size | --p-speechtotextbutton-pulse-size | Size of pulse, the ring around the button while listening |
| speechtotextbutton.pulse.duration | --p-speechtotextbutton-pulse-duration | Duration of pulse |
| speechtotextbutton.pulse.color | --p-speechtotextbutton-pulse-color | Color of pulse |

