voxxy

Reference v0.1.2

voxxy

The core: createVoxxy, the provider contracts, microphone recorder, audio player, model manager and sentence splitter.

import { … } from "voxxy"

Functions

claimMicrophone function

function claimMicrophone(who: string): () => void

One owner of the microphone at a time. Our recorder claims it for the length of a recording; the platform STT provider must claim it too, so the two never listen at once. Returns a function that releases the claim. Throws MicrophoneError("busy") if it is taken.

microphoneOwner function

function microphoneOwner(): string | null

Who holds the microphone now, or null. For state display and tests.

createWebAudioPlayer function

function createWebAudioPlayer(options?: WebAudioPlayerOptions): WebAudioPlayer

The Player that pcmSpeaker plugs into: WebAudio playback of PCM at whatever sample rate the model produces (the browser resamples), with buffers scheduled back to back on the audio clock, so a text handed over while the previous one plays starts exactly when it ends.

Call unlock() from a tap handler (the facade's voxxy.unlock() does). iOS and Chrome start audio only after a gesture, and iOS mutes WebAudio when the hardware silent switch is on unless the page asks for "playback" audio: unlock() applies the workaround chosen by silentSwitch.

createMicRecorder function

function createMicRecorder(options?: MicRecorderOptions): MicRecorder

Push-to-talk recorder: the Recorder that pcmListener plugs into. Yields mono 16 kHz Float32 PCM.

  • The audio context runs at whatever rate the device chose (44.1 or 48 kHz on iOS) and is resampled to 16 kHz here.
  • Capture uses an AudioWorklet where available, a ScriptProcessor otherwise.
  • The microphone is released when a recording ends, so the OS indicator goes away (see idleReleaseMs).
  • One recording at a time, and one owner of the microphone across the library (claimMicrophone).

start() should be called from a user gesture (the button press): the audio context needs one to run on iOS.

resample function

function resample(input: Float32Array, inRate: number, outRate?: number): Float32Array

Resamples a whole buffer at once.

createVoxxy function

function createVoxxy(options?: VoxxyOptions): Voxxy

Creates the handle a page talks to. It starts with no provider: pass one to select() (for example moonshineStt() or paradeeTts()), then call load(), listen() and speak().

Nothing is downloaded or loaded until the host asks, and the library draws no UI: consent, progress and text are the host's to show, from getState() and subscribe().

createCacheApiFileCache function

function createCacheApiFileCache(name?: string): FileCache

Weights in the Cache API. Chosen over OPFS because:

  • it works the same in a window and in a worker, so the adapter can read the files the host's downloader wrote;
  • cache.put() takes a streaming response and stores it all or nothing, which gives "a partial file never looks finished" for free;
  • OPFS writing needs createWritable (not in Safari before 26) or a sync access handle (workers only), so it needs more code paths for no gain here.

Both are cleared together by the browser's eviction, so neither is safer.

createMemoryConsentStore function

function createMemoryConsentStore(): ConsentStore

Keeps consent in memory only. Used as the fallback, and handy in tests.

createLocalStorageConsentStore function

function createLocalStorageConsentStore(): ConsentStore

Consent in localStorage, a place separate from the Cache API where the weights live. Consent is per kind *and* adapter: a different model has a different size, so the earlier "yes" does not cover it. Falls back to memory where localStorage is missing or throws (some private modes), in which case consent lasts until the page closes.

createModelManager function

function createModelManager(options?: ModelManagerOptions): ModelManager

Creates a model manager on its own, for a host that wants consent and downloads without the rest of voxxy. createVoxxy() builds one for you and exposes it as voxxy.models.

pcmListener function

function pcmListener(
  deps: {
    recorder: Recorder;
    transcribe(pcm16k: Float32Array, signal: AbortSignal): Promise<string>;
  }
): (options?: ListenOptions) => SttSession

Turns a recorder plus a PCM transcriber into listen().

pcmSpeaker function

function pcmSpeaker(
  deps: {
    synthesize(text: string, signal: AbortSignal): Promise<SynthesizedSpeech>;
    player: Player;
    maxAhead?: number;
    splitter?: SplitterOptions;
    now?: () => number;
    onChunk?: (info: ChunkInfo) => void;
  }
): {
    speak(text: string, options?: SpeakOptions): Promise<void>;
    stop(): void;
  }

Turns a PCM synthesiser plus a player into speak() / stop().

  • Chunks. A text is cut into sentences, and sentences are packed into chunks (splitter: at least minChars, at most maxChars; the first chunk has its own limits so that sound starts early). One chunk is one synthesis.
  • Pipeline. Calls queue in order. One chunk is synthesised at a time, and at most 1 + maxAhead are held (playing or waiting), which bounds the audio in memory. A finished chunk goes to the player at once, so the player can start it exactly when the one before ends.
  • No holes. A big chunk takes long to synthesise, and if the one before it is short, the listener hears silence while it is made. So the size of each chunk is capped by how much synthesis time the previous chunk's playing time can cover, at the speed measured on the chunks so far: on a fast device chunks may jump straight to their full size, on a slow one they grow step by step. A sentence is never split to fit, and the limit never makes a chunk smaller than one sentence.

speechWeight function

function speechWeight(text: string): number

How long a text takes to say, in characters of ordinary prose. Limits are counted in this, not in raw characters, because a digit is read as a word ("7" is "seven", "1999" is "nineteen ninety-nine") and a symbol as one too ("%" is "percent"): 80 digits are 80 characters on the page and almost half a minute of speech. A digit counts as 5, a symbol as 6, anything else as 1.

stripMarkdown function

function stripMarkdown(sentence: string): string

Strips what a speech engine would read aloud as noise: emphasis marks, code ticks, heading and list markers, link targets.

createSpeakStream function

function createSpeakStream(speaker: Speaker, options?: SpeakStreamOptions): SpeakStream

Speaks a reply while it is still being written. Text deltas go in; whole sentences go out to the provider's speak() one by one, in order, so the first sentence sounds while the rest is still arriving. It relies on speak() calls queueing, so it works for any provider: a PCM model prepares the next sentence while the current one plays, a platform engine queues natively. At most maxInFlight sentences are with the provider at once.

workerStt function

function workerStt(options: WorkerSttOptions): SttProvider

A speech-to-text provider backed by an adapter in its own worker. The worker starts on load() and ends on unload().

workerTts function

function workerTts(options: WorkerTtsOptions): TtsProvider

A text-to-speech provider backed by an adapter in its own worker. Queued speak() calls are synthesised ahead while the current one plays.

Classes

MicrophoneError class

class MicrophoneError extends Error

Everything that can go wrong with the microphone, as one type the host can switch on by code.

cause?: unknown
name: string
message: string
stack?: string
readonly code: MicrophoneErrorCode
constructor(
  code: MicrophoneErrorCode,
  message: string,
  options?: { cause?: unknown }
): MicrophoneError

AudioPlaybackError class

class AudioPlaybackError extends Error

Thrown when sound cannot start.

cause?: unknown
name: string
message: string
stack?: string
readonly code: "unsupported" | "blocked"

"blocked": the browser refused to start audio, usually because no tap or click came first (call unlock() from one). "unsupported": this browser has no WebAudio.

constructor(
  code: "unsupported" | "blocked",
  message: string
): AudioPlaybackError

Resampler class

class Resampler

Streaming sample-rate converter: a windowed-sinc low-pass (Blackman window) at the lower of the two Nyquist frequencies, so downsampling 44.1 or 48 kHz to 16 kHz does not fold high frequencies back into the speech band the way picking every n-th sample or plain interpolation does.

Feed chunks of any size to push(), then call flush() once at the end. Output does not depend on how the input was chunked. Edges are handled by normalising with the weights actually available.

constructor(inRate: number, outRate?: number, zeroCrossings?: number): Resampler
readonly inRate: number
readonly outRate: number
push(chunk: Float32Array): Float32Array
flush(): Float32Array

Emits the samples still waiting for input that will never come. Call once, after the last push().

ModelNotReadyError class

class ModelNotReadyError extends Error

Thrown by ensure() when the model is not downloaded and the user has not opted in.

cause?: unknown
name: string
message: string
stack?: string
constructor(message: string): ModelNotReadyError

ModelUnavailableError class

class ModelUnavailableError extends Error

Thrown by ensure() when check() says the provider cannot run here. message is the reason.

cause?: unknown
name: string
message: string
stack?: string
constructor(reason: string): ModelUnavailableError

SentenceSplitter class

class SentenceSplitter

Cuts streamed text into sentences as it arrives. push() returns the sentences that are complete; the text after the last sentence end stays buffered until more arrives or flush() is called. The result does not depend on how the text was cut into deltas.

It is a heuristic, not a parser: abbreviations ("Dr.", "e.g."), initials ("J. K. Rowling"), decimals ("3.5"), ellipses and quoted sentences are handled; a sentence that starts with a lower-case letter or a digit after a full stop is taken for a continuation. A sentence end is only recognised once the character after it has arrived (a stream cannot know that "3." is not about to become "3.5"), so a reply's last sentence waits for flush().

constructor(options?: SplitterOptions): SentenceSplitter
push(delta: string): string[]
flush(): string[]

The end of the text: everything still held comes out.

Interfaces

WebAudioPlayerOptions interface

interface WebAudioPlayerOptions

Options for createWebAudioPlayer. All of them are optional.

silentSwitch?: SilentSwitchMode

Which workaround to use for the hardware silent switch. Default "auto".

leadSeconds?: number

Delay between a buffer being scheduled on an idle player and it sounding, in seconds. Default 0.03.

createContext?: () => AudioContext

For tests: supply the context.

volume?: number

Output level from 0 (silent) to 1 (default). The audio still runs and is scheduled exactly as usual, only the master gain is set, so tests can exercise the real player without making a sound, in any browser.

ChunkTiming interface

interface ChunkTiming

When one queued buffer plays, as reported by the player's chunk-finished event.

startTime: number

On the audio clock (AudioContext.currentTime), in seconds.

endTime: number

PlayerEvents interface

interface PlayerEvents

The events a WebAudioPlayer emits, with what each one carries. Subscribe with player.on(name, handler).

started: undefined

Playback began after being idle (the first buffer is scheduled and will sound).

chunk-finished: ChunkTiming

One buffer finished. startTime of the next one equals this endTime when they were queued gaplessly.

drained: undefined

Nothing is playing or waiting any more.

WebAudioPlayer interface

interface WebAudioPlayer extends Player

Plays PCM. createWebAudioPlayer is the real one; voxxy/testing has a fake.

play() may be called while earlier buffers are still playing. The player then plays them in call order, each starting exactly when the previous one ends (gapless). pcmSpeaker relies on this: it hands over the next buffer as soon as it is synthesised.

unlock(): Promise<void>

Gets playback permitted. Call from a user gesture (a tap handler): iOS and Chrome start audio only after one. Safe to call repeatedly.

on<E extends keyof PlayerEvents>(event: E, handler: (payload: PlayerEvents[E]) => void): () => void
readonly contextState: AudioContextState | null

"suspended" until unlock() (or a gesture-driven play()) has run, then "running". null before any audio context exists.

readonly silentSwitchUsed: "audio-session" | "audio-element" | null

Which silent-switch workaround unlock() used, or null if none (yet).

dispose(): Promise<void>

Stops everything, releases the audio context and the silent element. The player can be used again.

play(pcm: Float32Array, sampleRate: number, signal: AbortSignal): Promise<void>

Resolves when this buffer has finished playing. Rejects with an AbortError when signal aborts, after silencing it (or without ever starting it, if its turn had not come).

MicRecorderOptions interface

interface MicRecorderOptions

Options for createMicRecorder. All of them are optional.

minDurationMs?: number

A recording shorter than this is rejected with MicrophoneError("too-short"). Default 250 ms.

maxDurationMs?: number

Audio past this length is dropped. Default 60 s.

onLimitReached?: () => void

Called once when maxDurationMs is reached, so the host can end push-to-talk.

onLevel?: (level: number) => void

Reports the RMS amplitude of each captured block on a linear 0–1 scale.

constraints?: MediaTrackConstraints

Merged into the getUserMedia audio constraints.

idleReleaseMs?: number

How long to keep the microphone open after a recording, so the next press starts at once. Default 0: the stream is released when recording stops, so the OS recording indicator goes away. Anything above 0 keeps that indicator on for that long.

preferWorklet?: boolean

Use an AudioWorklet where available (default). False forces the ScriptProcessor fallback.

MicRecorder interface

interface MicRecorder extends Recorder

Captures push-to-talk audio. createMicRecorder is the real one; voxxy/testing has a fake.

dispose(): Promise<void>

Releases the microphone and closes the audio context. The recorder can be used again afterwards.

start(signal?: AbortSignal): Promise<RecordingHandle>

Starts capturing. Rejects with an AbortError if signal aborts first.

VoxxyOptions interface

interface VoxxyOptions

Options for createVoxxy. All of them are optional.

models?: ModelManagerOptions

Where consent and weights are kept, and how files are fetched. The defaults suit a browser page.

platformFallback?: Partial<Record<Kind, PlatformFallbackPolicy>> & { lang?: string }

Browser engine policy per kind. Both default to any, which can send speech or text to a browser service.

ActiveProvider interface

interface ActiveProvider

The engine that listen() / speak() currently go to. The host can always read it, to show a notice if audio may leave the device.

id: string
engine: Engine
locality: Locality
reason: string | null

Why this one is in use when it is a fallback; null when it is simply what the host selected.

KindState interface

interface KindState

Everything the host can show about one kind, speech recognition (stt) or synthesis (tts).

selected: ProviderInfo<Kind> | null

What the host picked. Selecting downloads nothing.

active: ActiveProvider | null

Set while the provider is loaded and in use; null otherwise.

status: LoadStatus

Whether the provider is ready to use.

progress: { loaded: number; total: number | null } | null

Progress of getting the engine ready in memory (the download is on voxxy.models). total is null when unknown.

error: string | null

The message of the last load failure, or null.

fallbackError: string | null

Why the fallback was unavailable, when neither engine could load.

VoxxyState interface

interface VoxxyState

What voxxy.getState() returns and subscribe() listeners receive: one KindState for recognition and one for synthesis.

stt: KindState

Speech to text.

tts: KindState

Text to speech.

CallOptions interface

interface CallOptions

Options shared by calls that can be cancelled.

signal?: AbortSignal

Abort to cancel.

LoadOptions interface

interface LoadOptions extends CallOptions

Options for voxxy.load().

signal?: AbortSignal

Abort to cancel.

fallbackReason?: string

Ask for the allowed browser fallback directly and expose this reason in state.

SelectOptions interface

interface SelectOptions

Options for voxxy.select().

reason?: string

Recorded in active.reason. Used when a fallback policy picks the provider.

Voxxy interface

interface Voxxy

The host's handle. It owns the providers it was given: it loads and unloads them. A provider instance belongs to one Voxxy; sharing it between two is not supported.

models: ModelManager

Consent, download and storage state, per kind. Drive your consent popup and background-download indicator from this; load() uses it too.

platformModels: Pick<ModelManager, "getState"
  | "subscribe"
  | "optIn"
  | "optOut">

On-device browser recognition language pack. Separate from the selected model's consent and download.

getState(): VoxxyState
subscribe(listener: (state: VoxxyState) => void): () => void

Calls listener after every state change. Returns an unsubscribe function.

select(provider: SttProvider | TtsProvider, options?: SelectOptions): void

Picks the provider for its kind. Cancels a load in progress and unloads the previous provider of that kind. Downloads and loads nothing.

load(kind: Kind, options?: LoadOptions): Promise<void>

Gets the selected provider ready: asks the model manager first (consent, download), then loads it.

unload(kind: Kind): Promise<void>

Cancels a load in progress and unloads the provider. For a worker-backed one this ends the worker.

listen(options?: ListenOptions): SttSession

Starts push-to-talk on the active STT provider. Call stop() on the session for the text.

speak(text: string, options?: SpeakOptions): Promise<void>

Speaks on the active TTS provider. Calls queue; resolves when this utterance has finished.

speakStream(options?: SpeakStreamOptions): SpeakStream

Speaks a reply while it is still being written: push text deltas as they arrive and the first sentence sounds before the rest exists. Sentences go to speak() one by one, so it works with every provider. cancel() stops the sound too, so start a new reply by cancelling the old one. See SpeakStream.

stopSpeaking(): void

Stops speaking and clears the queue.

unlock(): Promise<void>

Call once from a user gesture (a tap or click handler, synchronously, before any await). iOS and Chrome start audio only after one, and iOS mutes WebAudio on the silent switch until the page asks for playback audio. Works on the selected providers whether or not they are loaded yet.

dispose(): Promise<void>

Unloads both providers.

ModelFile interface

interface ModelFile

One weight (or runtime) file an adapter needs.

url: string

Where the file comes from by default. Also the key it is stored under, so adapters read it back by this same string even when the host serves it from another place (see rewriteUrl).

size: number

Exact size in bytes. A download of any other size is rejected.

sha256?: string

Optional SHA-256, lowercase hex. Checked once, after the download. WebCrypto cannot hash a stream, so this reads the whole file into memory: use it for small files, or when integrity matters more than peak memory.

CheckResult interface

interface CheckResult

What InstallAcquisition.check() resolves to.

status: CheckStatus

Whether the thing is present, can be installed, or is out of reach.

reason?: string

Why it is unavailable (or cannot be installed), in words the host can show.

InstallAcquisition interface

interface InstallAcquisition

Something the platform installs for us, such as the browser's on-device recognition language pack. We cannot verify or evict it; the browser or OS owns it.

check(): Promise<CheckResult>

Side-effect free: no prompts, no downloads. The source of truth, asked again whenever the state matters.

install(
  signal: AbortSignal,
  onProgress?: (loaded: number, total: number | null) => void
): Promise<void>

Starts the installation and resolves when it is done. Called only after the user's opt-in. Absent where the platform offers no way to install (voices for speechSynthesis): then "installable" is treated as "unavailable" and there is no consent step. Progress is usually unknown (total null).

Acquirable interface

interface Acquirable

What the model manager needs from a provider: what must be on the device first. At most one of files (we download, verify and cache) and install (the platform does it).

readonly kind: Kind
readonly id: string
readonly downloadSize?: number | null

Approximate size for the consent text. For files the sum of their sizes is used when this is absent.

readonly files?: readonly ModelFile[]
readonly install?: InstallAcquisition

FileCache interface

interface FileCache

Where weights live. The default implementation uses the Cache API.

stat(url: string): Promise<number | null>

Size recorded when the file was stored, or null if it is absent. Cheap: does not read the body.

write(
  url: string,
  body: ReadableStream<Uint8Array<ArrayBufferLike>>,
  size: number
): Promise<void>

Stores the stream under url. All or nothing: if the stream errors, nothing is left behind, so a partly written file never looks finished.

read(url: string): Promise<Response | null>
delete(url: string): Promise<void>

ConsentRecord interface

interface ConsentRecord

What was agreed. Kept apart from the weights so it survives their eviction.

optedInAt: number
hasBeenReady: boolean

True once all files were verified at least once. Tells "never finished" from "evicted".

ConsentStore interface

interface ConsentStore

Where the user's choices are remembered, per kind and per adapter. The default keeps them in localStorage (with an in-memory fallback), and createMemoryConsentStore() suits tests. Provide your own to keep them elsewhere, for example on a server.

get(kind: Kind, adapterId: string): Promise<ConsentRecord | null>

The stored record, or null if the user has not opted in.

set(kind: Kind, adapterId: string, record: ConsentRecord): Promise<void>

Stores or replaces the record.

clear(kind: Kind, adapterId: string): Promise<void>

Forgets the choice, so the user is asked again.

DownloadProgress interface

interface DownloadProgress

How far a download has got, for a progress indicator.

loaded: number

Bytes present so far, counting files that were already cached.

total: number | null

Null when unknown, as for most platform installs.

fileIndex: number

Index (0-based) of the file being fetched, and how many files there are.

fileCount: number

ModelState interface

interface ModelState

Everything the host can show about one kind's model: phase, size, progress and errors.

provider: Acquirable | null

The provider registered for this kind, or null.

phase: ModelPhase

Where the model is, for choosing what to show.

downloadSize: number | null

For the host's consent text. Null when unknown or nothing is selected.

progress: DownloadProgress | null

Set while downloading.

error: string | null

The message of the failure, in phase error.

reason: string | null

Set in phase unavailable.

evicted: boolean

True when files that were once complete are now missing.

persisted: boolean | null

Result of navigator.storage.persist() at opt-in: true granted, false denied, null unavailable or not asked yet.

ModelsState interface

interface ModelsState

What voxxy.models.getState() returns: the model state of recognition and of synthesis.

stt: ModelState

Speech to text.

tts: ModelState

Text to speech.

ModelManagerOptions interface

interface ModelManagerOptions

Options for createModelManager and for createVoxxy({ models }). All of them are optional.

consent?: ConsentStore

Where consent is remembered. Default: localStorage.

cache?: FileCache

Where downloaded files are kept. Default: the Cache API.

fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>

Used for every download. Default: the global fetch.

rewriteUrl?: (url: string) => string

Serve weights from your own CDN: map a descriptor URL to the URL to fetch. The cache key stays the original.

autoDownload?: boolean

Start downloading as soon as consent exists (including after a reload or eviction). Default true.

persist?: () => Promise<boolean | null>

Asks the browser for persistent storage. Default: navigator.storage.persist().

progressIntervalMs?: number

Minimum gap between progress notifications, in ms. Default 100.

ModelManager interface

interface ModelManager

Owns consent, download and storage of the model files, per kind. It is independent of which provider runs the model. Drive the host's consent popup and its background-download indicator from getState().

getState(): ModelsState

The current state of both kinds.

subscribe(listener: (state: ModelsState) => void): () => void

Calls listener after every change. Returns an unsubscribe function.

register(provider: Acquirable): Promise<void>

Sets the provider for its kind and works out its phase from stored consent and what is present (cached files, or check() for an install). Replaces any earlier selection of that kind and stops its download. A provider with neither files nor install needs nothing and is ready at once, with no consent step.

optIn(kind: Kind): Promise<void>

Records consent, asks for persistent storage, and starts the download in the background. Resolves once started.

optOut(kind: Kind): Promise<void>

Stops any download, deletes the files and forgets the consent.

retry(kind: Kind): Promise<void>

Restarts after an error.

refresh(kind: Kind): Promise<void>

Re-checks the files. Notices eviction and, with consent, starts re-downloading.

ensure(kind: Kind, options?: { signal?: AbortSignal }): Promise<void>

Resolves when the model is ready, downloading it first if consent exists. Rejects with ModelNotReadyError without consent.

RecordingHandle interface

interface RecordingHandle

Mono 16 kHz samples, which is what PCM speech-to-text adapters take.

stop(): Promise<Float32Array<ArrayBufferLike>>

Stops recording and returns what was captured, mono 16 kHz.

cancel(): void

Stops recording and discards it.

Recorder interface

interface Recorder

Captures push-to-talk audio. createMicRecorder is the real one; voxxy/testing has a fake.

start(signal?: AbortSignal): Promise<RecordingHandle>

Starts capturing. Rejects with an AbortError if signal aborts first.

Player interface

interface Player

Plays PCM. createWebAudioPlayer is the real one; voxxy/testing has a fake.

play() may be called while earlier buffers are still playing. The player then plays them in call order, each starting exactly when the previous one ends (gapless). pcmSpeaker relies on this: it hands over the next buffer as soon as it is synthesised.

play(pcm: Float32Array, sampleRate: number, signal: AbortSignal): Promise<void>

Resolves when this buffer has finished playing. Rejects with an AbortError when signal aborts, after silencing it (or without ever starting it, if its turn had not come).

unlock(): Promise<void>

Gets playback permitted. Call from a user gesture (a tap handler): iOS and Chrome start audio only after one. Safe to call repeatedly.

ChunkInfo interface

interface ChunkInfo

What pcmSpeaker reports about each chunk once it has been synthesised.

index: number

Which chunk of its speak() call this is, from 0.

text: string
weight: number

Its length in speech weight (see speechWeight).

synthMs: number

How long the synthesis took.

audioSeconds: number

How long the speech is.

speedFactor: number | undefined

How many times faster than speech the device was on the chunks so far, or undefined before the first.

nextCap: number | undefined

The most the next chunk may weigh given that speed, or undefined if nothing limits it.

ProviderLoadContext interface

interface ProviderLoadContext

What the facade hands to a provider's load(): a progress callback and a way to cancel.

onProgress?: (loaded: number, total: number | null) => void

Progress of getting the engine ready in memory (not the download, which voxxy.models reports).

signal?: AbortSignal

Aborted when the host cancels the load.

ProviderInfo interface

interface ProviderInfo<K extends Kind = Kind>

What every provider says about itself. Read-only data, safe to put in state.

readonly kind: K
readonly id: string
readonly engine: Engine
readonly locality: Locality
readonly downloadSize?: number | null

For the consent text. Falls back to the sum of files; null or absent when unknown.

Provider interface

interface Provider<K extends Kind = Kind> extends ProviderInfo<K>

Common to both kinds. A provider owns whatever it needs to produce text or sound (microphone, playback, worker); the core never reaches inside. The host creates it, passes it to voxxy.select(), and one provider belongs to one Voxxy instance: sharing it between two is not supported.

readonly kind: K
readonly id: string
readonly engine: Engine
readonly locality: Locality
readonly downloadSize?: number | null

For the consent text. Falls back to the sum of files; null or absent when unknown.

readonly files?: readonly ModelFile[]

What must be on the device before this provider can run. At most one of: files (we download, verify and cache them) or install (the platform does it). Neither: no consent step, load() runs at once.

readonly install?: InstallAcquisition
load(context?: ProviderLoadContext & { models?: ModelFileReader }): Promise<void>

Gets the engine ready (starts the worker, loads the model). Called after any acquisition is done.

unload(): Promise<void>

Releases everything. For a worker-backed provider this ends the worker, which is what returns WASM memory.

unlock(): Promise<void>

Gets what only a user gesture can get: audio output on iOS and Chrome, for example. The facade's voxxy.unlock() calls it, so the host calls that once from a tap handler. Optional: absent where there is nothing to unlock.

SttSession interface

interface SttSession

One push-to-talk recording, returned by voxxy.listen(). Call stop() when the button is released, or cancel() to drop it.

stop(): Promise<string>

Ends the recording and resolves with the final text.

cancel(): void

Drops the recording and any transcription in progress. stop() then rejects with an AbortError.

ListenOptions interface

interface ListenOptions

Options for listen().

signal?: AbortSignal

Abort to drop the recording, like cancel() on the session.

SttProvider interface

interface SttProvider extends Provider<"stt">

Push-to-talk speech recognition. No streaming partial results in the interface.

readonly kind: "stt"
readonly id: string
readonly engine: Engine
readonly locality: Locality
readonly downloadSize?: number | null

For the consent text. Falls back to the sum of files; null or absent when unknown.

readonly files?: readonly ModelFile[]

What must be on the device before this provider can run. At most one of: files (we download, verify and cache them) or install (the platform does it). Neither: no consent step, load() runs at once.

readonly install?: InstallAcquisition
load(context?: ProviderLoadContext & { models?: ModelFileReader }): Promise<void>

Gets the engine ready (starts the worker, loads the model). Called after any acquisition is done.

unload(): Promise<void>

Releases everything. For a worker-backed provider this ends the worker, which is what returns WASM memory.

unlock(): Promise<void>

Gets what only a user gesture can get: audio output on iOS and Chrome, for example. The facade's voxxy.unlock() calls it, so the host calls that once from a tap handler. Optional: absent where there is nothing to unlock.

listen(options?: ListenOptions): SttSession

SpeakOptions interface

interface SpeakOptions

Options for speak().

signal?: AbortSignal

Abort to cancel this utterance: it stops if it is playing, or is dropped from the queue. The returned promise rejects with an AbortError.

TtsProvider interface

interface TtsProvider extends Provider<"tts">

Speech synthesis that plays the sound itself.

readonly kind: "tts"
readonly id: string
readonly engine: Engine
readonly locality: Locality
readonly downloadSize?: number | null

For the consent text. Falls back to the sum of files; null or absent when unknown.

readonly files?: readonly ModelFile[]

What must be on the device before this provider can run. At most one of: files (we download, verify and cache them) or install (the platform does it). Neither: no consent step, load() runs at once.

readonly install?: InstallAcquisition
load(context?: ProviderLoadContext & { models?: ModelFileReader }): Promise<void>

Gets the engine ready (starts the worker, loads the model). Called after any acquisition is done.

unload(): Promise<void>

Releases everything. For a worker-backed provider this ends the worker, which is what returns WASM memory.

unlock(): Promise<void>

Gets what only a user gesture can get: audio output on iOS and Chrome, for example. The facade's voxxy.unlock() calls it, so the host calls that once from a tap handler. Optional: absent where there is nothing to unlock.

speak(text: string, options?: SpeakOptions): Promise<void>

Resolves when this utterance has finished playing. Calls queue: a speak made while another is playing starts after it, in order.

stop(): void

Clears the queue and stops the sound. Pending speak promises reject with an AbortError.

SplitterOptions interface

interface SplitterOptions

How text is cut into pieces for speech: where sentences end, how short ones are packed together, and how the first sound is kept quick. Passed to speak() through the TTS provider's splitter option, and to speakStream().

maxChars?: number

A run of text with no sentence end is cut after about this many characters. Default 220.

minChars?: number

Sentences are packed together until they reach this length, because speech models do poorly on very short utterances (Kokoro's authors put the sweet spot at 100–200 tokens) and every utterance costs a quiet moment at its start. A sentence shorter than this is held and joined to the next one; the end of the text flushes it. The packed text never grows past maxChars. Default 10, which only mends tiny fragments; around 120 packs several sentences per chunk. 0 turns this off.

firstMinChars?: number

The same, for the very first chunk only. Keep it small so sound starts after one short sentence, and let minChars pack everything after it. Default: the same as minChars.

firstMaxChars?: number

The longest the very first chunk may be. The wait before the first sound is the time to synthesise this chunk, and it grows with its length (about 0.4 s for 100 characters on a laptop, several times that on a phone), so a long first sentence is cut at a pause (a comma, a dash) instead of being spoken whole. Later chunks use maxChars. Default: 120, or maxChars if that is smaller.

newlines?: "smart" | "break" | "space"

What a line break means.

  • "smart" (default): a break is a sentence end after a line that ends with a full stop, a colon and the like, before a list marker, before a blank line, and between short lines (headings, verse). A line that stops without punctuation and is long, or is followed by a lower-case word, is a line cut at the margin of hard-wrapped text, an e-mail or a PDF, so the sentence goes on.
  • "break": every line break ends a sentence.
  • "space": a line break is a space.

SpeakStreamOptions interface

interface SpeakStreamOptions extends SplitterOptions

Options for voxxy.speakStream(): the sentence-splitting ones plus limits on how far text may run ahead of the voice.

maxChars?: number

A run of text with no sentence end is cut after about this many characters. Default 220.

minChars?: number

Sentences are packed together until they reach this length, because speech models do poorly on very short utterances (Kokoro's authors put the sweet spot at 100–200 tokens) and every utterance costs a quiet moment at its start. A sentence shorter than this is held and joined to the next one; the end of the text flushes it. The packed text never grows past maxChars. Default 10, which only mends tiny fragments; around 120 packs several sentences per chunk. 0 turns this off.

firstMinChars?: number

The same, for the very first chunk only. Keep it small so sound starts after one short sentence, and let minChars pack everything after it. Default: the same as minChars.

firstMaxChars?: number

The longest the very first chunk may be. The wait before the first sound is the time to synthesise this chunk, and it grows with its length (about 0.4 s for 100 characters on a laptop, several times that on a phone), so a long first sentence is cut at a pause (a comma, a dash) instead of being spoken whole. Later chunks use maxChars. Default: 120, or maxChars if that is smaller.

newlines?: "smart" | "break" | "space"

What a line break means.

  • "smart" (default): a break is a sentence end after a line that ends with a full stop, a colon and the like, before a list marker, before a blank line, and between short lines (headings, verse). A line that stops without punctuation and is long, or is followed by a lower-case word, is a line cut at the margin of hard-wrapped text, an e-mail or a PDF, so the sentence goes on.
  • "break": every line break ends a sentence.
  • "space": a line break is a space.
maxInFlight?: number

How many sentences may be handed to the provider at once: the one playing plus those queued behind it. Default 2. This bounds the audio held in memory, since a PCM provider synthesises every sentence it was given.

maxPending?: number

How many finished sentences may wait here for their turn before push() makes the caller wait. Default 8. Text is cheap, so this is about keeping a fast text source from running far ahead of the voice.

normalize?: (sentence: string) => string

Tidies a sentence before it is spoken. Default: removes Markdown marks. Return "" to skip the sentence.

signal?: AbortSignal

Cancels the stream, like cancel().

SpeakStream interface

interface SpeakStream

A reply being spoken while it is still being written, returned by voxxy.speakStream(). Feed it with push(), finish with end(), or stop with cancel().

push(delta: string): Promise<void>

Adds text as it arrives, in any size of piece. The returned promise resolves at once while there is room, and waits while many sentences are already waiting: await it in a loop over a token stream to let the speech set the pace.

end(): Promise<void>

No more text. Resolves when everything pushed has finished playing; rejects if the stream was cancelled or the provider failed.

cancel(): void

Drops what is waiting, stops the sound, and makes end() reject with an AbortError.

Speaker interface

interface Speaker

What a stream needs from a speaker: voxxy.speak and voxxy.stopSpeaking, or any provider's speak and stop.

speak(text: string, options?: SpeakOptions): Promise<void>
stop(): void

AdapterLoadContext interface

interface AdapterLoadContext

Passed to an adapter's load(). Everything here is optional so adapters stay easy to test.

onProgress?: (loaded: number, total: number | null) => void

total is null when unknown.

signal?: AbortSignal

Aborted when the host cancels the load. Adapters should stop what they are doing.

wasmBaseUrl?: string

Where the adapter should fetch its WASM runtime files from, if the host overrides it.

options?: unknown

What the provider factory passed as adapterOptions (structured-cloneable): for example the URLs its files were declared under.

models?: ModelFileReader

Reads the files the host downloaded, by the url the provider declared. Absent where there is no Cache API.

SttAdapter interface

interface SttAdapter

Speech-to-text engine inside a worker: mono 16 kHz PCM in, text out. The PCM layer under a worker-backed SttProvider; hosts normally use the provider.

readonly id: string
load(context?: AdapterLoadContext): Promise<void>
transcribe(pcm16k: Float32Array, signal?: AbortSignal): Promise<string>
dispose(): Promise<void>

SpeechResult interface

interface SpeechResult

What a TtsAdapter returns: the synthesised sound.

pcm: Float32Array

Mono samples in the range -1 to 1.

sampleRate: number

Samples per second of pcm. It differs per model.

TtsAdapter interface

interface TtsAdapter

Text-to-speech engine inside a worker: text in, PCM plus its sample rate out. Phonemisation is the adapter's own business.

readonly id: string
load(context?: AdapterLoadContext): Promise<void>
synthesize(text: string, signal?: AbortSignal): Promise<SpeechResult>
dispose(): Promise<void>

WorkerSttOptions interface

interface WorkerSttOptions extends WorkerProviderOptions

Options for workerStt: the shared ones plus the recorder that captures the microphone.

id: string
spawn(workerUrl?: string | URL): Worker

Creates this provider's worker. Lives in each adapter's entry point, because bundlers only emit the worker script for the literal form new Worker(new URL("./x.worker.js", import.meta.url), { type: "module" }). workerUrl is the host's override, when it serves the script itself.

workerUrl?: string | URL
wasmBaseUrl?: string

Where the adapter fetches its WASM runtime files from, when they are not already in storage.

adapterOptions?: unknown

Handed to the adapter's load() as context.options. Must be structured-cloneable.

files?: readonly ModelFile[]

Weights to download before load(). The manager checks, downloads and verifies them.

downloadSize?: number
recorder: Recorder

Captures mono 16 kHz audio. createMicRecorder is the real one.

WorkerTtsOptions interface

interface WorkerTtsOptions extends WorkerProviderOptions

Options for workerTts: the shared ones plus the player that plays the sound.

id: string
spawn(workerUrl?: string | URL): Worker

Creates this provider's worker. Lives in each adapter's entry point, because bundlers only emit the worker script for the literal form new Worker(new URL("./x.worker.js", import.meta.url), { type: "module" }). workerUrl is the host's override, when it serves the script itself.

workerUrl?: string | URL
wasmBaseUrl?: string

Where the adapter fetches its WASM runtime files from, when they are not already in storage.

adapterOptions?: unknown

Handed to the adapter's load() as context.options. Must be structured-cloneable.

files?: readonly ModelFile[]

Weights to download before load(). The manager checks, downloads and verifies them.

downloadSize?: number
player: Player

Plays PCM. createWebAudioPlayer is the real one.

maxAhead?: number

How many texts may be synthesised ahead of the one playing. Default 1.

splitter?: SplitterOptions

How speak() cuts long text into sentences before synthesising them one by one.

onChunk?: (info: ChunkInfo) => void

Called for every chunk once it is synthesised: its text, size, how long it took and how long it plays. For logs and the stand.

Types

MicrophoneErrorCode type

type MicrophoneErrorCode = "permission-denied"
  | "no-device"
  | "in-use"
  | "unsupported"
  | "busy"
  | "too-short"
  | "failed"

Why the microphone could not be used. Carried by MicrophoneError.code, so a host can show a message for each case.

SilentSwitchMode type

type SilentSwitchMode = "auto"
  | "audio-session"
  | "audio-element"
  | "off"

How the player gets sound out on an iPhone whose hardware silent switch is on, where WebAudio is otherwise muted. Pick one with the silentSwitch option of createWebAudioPlayer.

PlatformFallbackPolicy type

type PlatformFallbackPolicy = "any" | "local-only" | "off"

When the selected model is unavailable (the user declined the download, or loading failed), may voxxy use the browser's own speech engine instead? "any": yes, even one that sends audio or text to a browser service. "local-only": only an engine that works on the device. "off": never.

LoadStatus type

type LoadStatus = "idle" | "loading" | "ready" | "error"

Where a provider is in getting ready: idle (not asked yet), loading, ready to use, or error (see KindState.error).

CheckStatus type

type CheckStatus = "ready" | "installable" | "unavailable"

The answer of InstallAcquisition.check(): ready (already on the device), installable (the user can opt in and the platform will install it) or unavailable (cannot be used here).

ModelFileReader type

type ModelFileReader = Pick<FileCache, "read">

What the host or adapter may read; a subset of FileCache.

ModelPhase type

type ModelPhase = "not-opted-in"
  | "opted-in-not-downloaded"
  | "downloading"
  | "ready"
  | "evicted-redownloading"
  | "unavailable"
  | "error"

Where one kind's model is: what the host should show, and whether to ask for consent.

Engine type

type Engine = "worker" | "platform" | "custom"

Where the work happens. worker: our own models in a Web Worker. platform: the browser's engine. custom: the host's.

Locality type

type Locality = "local" | "cloud" | "unknown"

Whether audio or text leaves the device. Fixed per provider instance: where one engine can run both ways, the module offers two instances.

Kind type

type Kind = "stt" | "tts"

The two things voxxy does: "stt" is speech to text, "tts" is text to speech.

Variables

STT_SAMPLE_RATE const

const STT_SAMPLE_RATE: 16000

Models take mono 16 kHz audio.