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): () => voidOne 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 | nullWho holds the microphone now, or null. For state display and tests.
createWebAudioPlayer function
function createWebAudioPlayer(options?: WebAudioPlayerOptions): WebAudioPlayerThe 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): MicRecorderPush-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): Float32ArrayResamples a whole buffer at once.
createVoxxy function
function createVoxxy(options?: VoxxyOptions): VoxxyCreates 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): FileCacheWeights 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(): ConsentStoreKeeps consent in memory only. Used as the fallback, and handy in tests.
createLocalStorageConsentStore function
function createLocalStorageConsentStore(): ConsentStoreConsent 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): ModelManagerCreates 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) => SttSessionTurns 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 leastminChars, at mostmaxChars; 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 + maxAheadare 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): numberHow 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): stringStrips 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): SpeakStreamSpeaks 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): SttProviderA 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): TtsProviderA 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 ErrorEverything that can go wrong with the microphone, as one type the host can switch on by code.
cause?: unknownname: stringmessage: stringstack?: stringreadonly code: MicrophoneErrorCodeconstructor(
code: MicrophoneErrorCode,
message: string,
options?: { cause?: unknown }
): MicrophoneErrorAudioPlaybackError class
class AudioPlaybackError extends ErrorThrown when sound cannot start.
cause?: unknownname: stringmessage: stringstack?: stringreadonly 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
): AudioPlaybackErrorResampler class
class ResamplerStreaming 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): Resamplerreadonly inRate: numberreadonly outRate: numberpush(chunk: Float32Array): Float32Arrayflush(): Float32ArrayEmits the samples still waiting for input that will never come. Call once, after the last push().
ModelNotReadyError class
class ModelNotReadyError extends ErrorThrown by ensure() when the model is not downloaded and the user has not opted in.
cause?: unknownname: stringmessage: stringstack?: stringconstructor(message: string): ModelNotReadyErrorSentenceSplitter class
class SentenceSplitterCuts 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): SentenceSplitterpush(delta: string): string[]flush(): string[]The end of the text: everything still held comes out.
Interfaces
WebAudioPlayerOptions interface
interface WebAudioPlayerOptionsOptions for createWebAudioPlayer. All of them are optional.
silentSwitch?: SilentSwitchModeWhich workaround to use for the hardware silent switch. Default "auto".
leadSeconds?: numberDelay between a buffer being scheduled on an idle player and it sounding, in seconds. Default 0.03.
createContext?: () => AudioContextFor tests: supply the context.
volume?: numberOutput 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 ChunkTimingWhen one queued buffer plays, as reported by the player's chunk-finished event.
startTime: numberOn the audio clock (AudioContext.currentTime), in seconds.
endTime: numberPlayerEvents interface
interface PlayerEventsThe events a WebAudioPlayer emits, with what each one carries. Subscribe with player.on(name, handler).
started: undefinedPlayback began after being idle (the first buffer is scheduled and will sound).
chunk-finished: ChunkTimingOne buffer finished. startTime of the next one equals this endTime when they were queued gaplessly.
drained: undefinedNothing is playing or waiting any more.
WebAudioPlayer interface
interface WebAudioPlayer extends PlayerPlays 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): () => voidreadonly 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" | nullWhich 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 MicRecorderOptionsOptions for createMicRecorder. All of them are optional.
minDurationMs?: numberA recording shorter than this is rejected with MicrophoneError("too-short"). Default 250 ms.
maxDurationMs?: numberAudio past this length is dropped. Default 60 s.
onLimitReached?: () => voidCalled once when maxDurationMs is reached, so the host can end push-to-talk.
onLevel?: (level: number) => voidReports the RMS amplitude of each captured block on a linear 0–1 scale.
constraints?: MediaTrackConstraintsMerged into the getUserMedia audio constraints.
idleReleaseMs?: numberHow 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?: booleanUse an AudioWorklet where available (default). False forces the ScriptProcessor fallback.
MicRecorder interface
interface MicRecorder extends RecorderCaptures 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 VoxxyOptionsOptions for createVoxxy. All of them are optional.
models?: ModelManagerOptionsWhere 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 ActiveProviderThe engine that listen() / speak() currently go to. The host can always read it, to show a notice if audio may leave the device.
KindState interface
interface KindStateEverything the host can show about one kind, speech recognition (stt) or synthesis (tts).
selected: ProviderInfo<Kind> | nullWhat the host picked. Selecting downloads nothing.
active: ActiveProvider | nullSet while the provider is loaded and in use; null otherwise.
status: LoadStatusWhether the provider is ready to use.
progress: { loaded: number; total: number | null } | nullProgress of getting the engine ready in memory (the download is on voxxy.models). total is null when unknown.
error: string | nullThe message of the last load failure, or null.
fallbackError: string | nullWhy the fallback was unavailable, when neither engine could load.
VoxxyState interface
interface VoxxyStateWhat voxxy.getState() returns and subscribe() listeners receive: one KindState for recognition and one for synthesis.
CallOptions interface
interface CallOptionsOptions shared by calls that can be cancelled.
signal?: AbortSignalAbort to cancel.
LoadOptions interface
interface LoadOptions extends CallOptionsOptions for voxxy.load().
signal?: AbortSignalAbort to cancel.
fallbackReason?: stringAsk for the allowed browser fallback directly and expose this reason in state.
SelectOptions interface
interface SelectOptionsOptions for voxxy.select().
reason?: stringRecorded in active.reason. Used when a fallback policy picks the provider.
Voxxy interface
interface VoxxyThe 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: ModelManagerConsent, 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(): VoxxyStatesubscribe(listener: (state: VoxxyState) => void): () => voidCalls listener after every state change. Returns an unsubscribe function.
select(provider: SttProvider | TtsProvider, options?: SelectOptions): voidPicks 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): SttSessionStarts 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): SpeakStreamSpeaks 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(): voidStops 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 ModelFileOne weight (or runtime) file an adapter needs.
url: stringWhere 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: numberExact size in bytes. A download of any other size is rejected.
sha256?: stringOptional 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 CheckResultWhat InstallAcquisition.check() resolves to.
status: CheckStatusWhether the thing is present, can be installed, or is out of reach.
reason?: stringWhy it is unavailable (or cannot be installed), in words the host can show.
InstallAcquisition interface
interface InstallAcquisitionSomething 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 AcquirableWhat 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: Kindreadonly id: stringreadonly downloadSize?: number | nullApproximate size for the consent text. For files the sum of their sizes is used when this is absent.
readonly files?: readonly ModelFile[]readonly install?: InstallAcquisitionFileCache interface
interface FileCacheWhere 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 ConsentRecordWhat was agreed. Kept apart from the weights so it survives their eviction.
optedInAt: numberhasBeenReady: booleanTrue once all files were verified at least once. Tells "never finished" from "evicted".
ConsentStore interface
interface ConsentStoreWhere 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 DownloadProgressHow far a download has got, for a progress indicator.
loaded: numberBytes present so far, counting files that were already cached.
total: number | nullNull when unknown, as for most platform installs.
fileIndex: numberIndex (0-based) of the file being fetched, and how many files there are.
fileCount: numberModelState interface
interface ModelStateEverything the host can show about one kind's model: phase, size, progress and errors.
provider: Acquirable | nullThe provider registered for this kind, or null.
phase: ModelPhaseWhere the model is, for choosing what to show.
downloadSize: number | nullFor the host's consent text. Null when unknown or nothing is selected.
progress: DownloadProgress | nullSet while downloading.
error: string | nullThe message of the failure, in phase error.
reason: string | nullSet in phase unavailable.
evicted: booleanTrue when files that were once complete are now missing.
persisted: boolean | nullResult of navigator.storage.persist() at opt-in: true granted, false denied, null unavailable or not asked yet.
ModelsState interface
interface ModelsStateWhat voxxy.models.getState() returns: the model state of recognition and of synthesis.
stt: ModelStateSpeech to text.
tts: ModelStateText to speech.
ModelManagerOptions interface
interface ModelManagerOptionsOptions for createModelManager and for createVoxxy({ models }). All of them are optional.
consent?: ConsentStoreWhere consent is remembered. Default: localStorage.
cache?: FileCacheWhere 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) => stringServe weights from your own CDN: map a descriptor URL to the URL to fetch. The cache key stays the original.
autoDownload?: booleanStart 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?: numberMinimum gap between progress notifications, in ms. Default 100.
ModelManager interface
interface ModelManagerOwns 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(): ModelsStateThe current state of both kinds.
subscribe(listener: (state: ModelsState) => void): () => voidCalls 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 RecordingHandleMono 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(): voidStops recording and discards it.
Recorder interface
interface RecorderCaptures 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 PlayerPlays 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 ChunkInfoWhat pcmSpeaker reports about each chunk once it has been synthesised.
index: numberWhich chunk of its speak() call this is, from 0.
text: stringweight: numberIts length in speech weight (see speechWeight).
synthMs: numberHow long the synthesis took.
audioSeconds: numberHow long the speech is.
speedFactor: number | undefinedHow many times faster than speech the device was on the chunks so far, or undefined before the first.
nextCap: number | undefinedThe most the next chunk may weigh given that speed, or undefined if nothing limits it.
ProviderLoadContext interface
interface ProviderLoadContextWhat the facade hands to a provider's load(): a progress callback and a way to cancel.
onProgress?: (loaded: number, total: number | null) => voidProgress of getting the engine ready in memory (not the download, which voxxy.models reports).
signal?: AbortSignalAborted 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.
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: Kreadonly id: stringreadonly engine: Enginereadonly locality: Localityreadonly downloadSize?: number | nullFor 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?: InstallAcquisitionload(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 SttSessionOne 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(): voidDrops the recording and any transcription in progress. stop() then rejects with an AbortError.
ListenOptions interface
interface ListenOptionsOptions for listen().
signal?: AbortSignalAbort 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: stringreadonly engine: Enginereadonly locality: Localityreadonly downloadSize?: number | nullFor 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?: InstallAcquisitionload(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): SttSessionSpeakOptions interface
interface SpeakOptionsOptions for speak().
signal?: AbortSignalAbort 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: stringreadonly engine: Enginereadonly locality: Localityreadonly downloadSize?: number | nullFor 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?: InstallAcquisitionload(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(): voidClears the queue and stops the sound. Pending speak promises reject with an AbortError.
SplitterOptions interface
interface SplitterOptionsHow 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?: numberA run of text with no sentence end is cut after about this many characters. Default 220.
minChars?: numberSentences 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?: numberThe 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?: numberThe 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 SplitterOptionsOptions for voxxy.speakStream(): the sentence-splitting ones plus limits on how far text may run ahead of the voice.
maxChars?: numberA run of text with no sentence end is cut after about this many characters. Default 220.
minChars?: numberSentences 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?: numberThe 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?: numberThe 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?: numberHow 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?: numberHow 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) => stringTidies a sentence before it is spoken. Default: removes Markdown marks. Return "" to skip the sentence.
signal?: AbortSignalCancels the stream, like cancel().
SpeakStream interface
interface SpeakStreamA 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(): voidDrops what is waiting, stops the sound, and makes end() reject with an AbortError.
Speaker interface
interface SpeakerWhat 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(): voidAdapterLoadContext interface
interface AdapterLoadContextPassed to an adapter's load(). Everything here is optional so adapters stay easy to test.
onProgress?: (loaded: number, total: number | null) => voidtotal is null when unknown.
signal?: AbortSignalAborted when the host cancels the load. Adapters should stop what they are doing.
wasmBaseUrl?: stringWhere the adapter should fetch its WASM runtime files from, if the host overrides it.
options?: unknownWhat the provider factory passed as adapterOptions (structured-cloneable): for example the URLs its files were declared under.
models?: ModelFileReaderReads the files the host downloaded, by the url the provider declared. Absent where there is no Cache API.
SttAdapter interface
interface SttAdapterSpeech-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: stringload(context?: AdapterLoadContext): Promise<void>transcribe(pcm16k: Float32Array, signal?: AbortSignal): Promise<string>dispose(): Promise<void>SpeechResult interface
interface SpeechResultWhat a TtsAdapter returns: the synthesised sound.
pcm: Float32ArrayMono samples in the range -1 to 1.
sampleRate: numberSamples per second of pcm. It differs per model.
TtsAdapter interface
interface TtsAdapterText-to-speech engine inside a worker: text in, PCM plus its sample rate out. Phonemisation is the adapter's own business.
readonly id: stringload(context?: AdapterLoadContext): Promise<void>synthesize(text: string, signal?: AbortSignal): Promise<SpeechResult>dispose(): Promise<void>WorkerSttOptions interface
interface WorkerSttOptions extends WorkerProviderOptionsOptions for workerStt: the shared ones plus the recorder that captures the microphone.
id: stringspawn(workerUrl?: string | URL): WorkerCreates 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 | URLwasmBaseUrl?: stringWhere the adapter fetches its WASM runtime files from, when they are not already in storage.
adapterOptions?: unknownHanded 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?: numberrecorder: RecorderCaptures mono 16 kHz audio. createMicRecorder is the real one.
WorkerTtsOptions interface
interface WorkerTtsOptions extends WorkerProviderOptionsOptions for workerTts: the shared ones plus the player that plays the sound.
id: stringspawn(workerUrl?: string | URL): WorkerCreates 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 | URLwasmBaseUrl?: stringWhere the adapter fetches its WASM runtime files from, when they are not already in storage.
adapterOptions?: unknownHanded 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?: numberplayer: PlayerPlays PCM. createWebAudioPlayer is the real one.
maxAhead?: numberHow many texts may be synthesised ahead of the one playing. Default 1.
splitter?: SplitterOptionsHow speak() cuts long text into sentences before synthesising them one by one.
onChunk?: (info: ChunkInfo) => voidCalled 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: 16000Models take mono 16 kHz audio.