The main class for managing Web Speech API voices with enhanced functionality.
static initialize(options?: {
languages?: string[];
maxTimeout?: number;
interval?: number;
}): Promise<WebSpeechVoiceManager>
Creates and initializes a new WebSpeechVoiceManager instance. This static factory method must be called to create an instance.
languages: Optional array of preferred language codes to filter voices during initializationmaxTimeout: Maximum time in milliseconds to wait for voices to load (default: 10000ms)interval: Interval in milliseconds between voice loading checks (default: 10ms)Returns a Promise that resolves with a WebSpeechSpeechManager instance. This instance is a singleton to ensure the same voice manager is used whether initialized directly or through the PlaybackEngine.
Calling initialize() again on an already-initialized singleton doesn’t create a new instance or reset it — it broadens the existing one to also cover any newly requested languages, keeping voices already loaded for earlier languages. Omitting languages on that later call is a no-op (not a retroactive “load everything”); only the very first call’s absence of languages loads every voice. A WebSpeechEngine already initialized gets the newly covered voices too, in getAvailableVoices() and for an utterance’s voice.
By default, the instance keeps all voices in memory. You can filter them using the getVoices method with optional filter criteria and use this array instead.
voiceManager.getVoices(options?: VoiceFilterOptions): ReadiumSpeechVoice[]
Fetches all available voices that match the specified filter criteria.
interface VoiceFilterOptions {
languages?: string | string[]; // Filter by language code(s) (e.g., "en", "fr-FR")
source?: TSource; // Filter by voice source ("json" | "browser")
gender?: TGender; // "male" | "female" | "neutral"
quality?: TQuality | TQuality[]; // "veryHigh" | "high" | "normal" | "low" | "veryLow" | null
offlineOnly?: boolean; // Only return voices available offline
provider?: string; // Filter by voice provider
excludeNovelty?: boolean; // Exclude novelty voices, true by default
excludeVeryLowQuality?: boolean; // Exclude very low quality voices, true by default
removeDuplicates?: boolean; // Remove duplicate voices, true by default
}
By default, this method returns all voices, excluding novelty voices and very low quality voices, as well as removing what can be considered duplicate voices (lower quality, online/offline, etc).
A voice’s quality is the first of:
compact/super-compact ("low"), enhanced ("normal") or premium ("high") segment of its voiceURI, between ., _ or -: com.apple.speech.synthesis.voice.enhanced.samantha is "normal";nativeID;localizedName, Apple’s word for enhanced or premium in its voiceURI (apple.json), in the system’s language: the first whose words for both appear in the browser’s voice names, else the user’s first preferred language;quality, picked by how many voices of that language and name (see Duplicates) the browser has: the 2nd for 2, capped at the last;null.With removeDuplicates, voices of the same language and name (the JSON name, else the browser’s), ignoring case, parentheses and punctuation other than hyphens, are kept once:
altNames naming the other, or both share one: the one of highest quality, then the one the browser names as the JSON name, else the one whose name comes first in altNames;quality, the later one in the browser’s list on a tie.voiceManager.getLanguages(localization?: string, filterOptions?: VoiceFilterOptions, voices?: ReadiumSpeechVoice[]): LanguageInfo[]
voiceManager.getRegions(localization?: string, filterOptions?: VoiceFilterOptions, voices?: ReadiumSpeechVoice[]): LanguageInfo[]
Returns arrays of languages and regions with their display names and voice counts. Both methods preserve the order of first occurrence when custom voices are provided.
voiceManager.getBrowserLanguages(localization?: string): LanguageInfo[]
Returns the languages of every voice the browser has, sorted by name, including languages initialize() wasn’t called with. Their voice data isn’t loaded, so it is cheap, but no voice is filtered out either: initialize with a language to get its voices.
async voiceManager.getDefaultVoice(languages: string | string[], voices?: ReadiumSpeechVoice[]): Promise<ReadiumSpeechVoice | null>
Automatically selects the best available voice based on quality and language preferences. This is the recommended method for getting a suitable voice without manual selection.
// Get the best voice for user's browser language
const defaultVoice = await voiceManager.getDefaultVoice(navigator.languages);
// Get the best voice for specific preferred languages
const frenchVoice = await voiceManager.getDefaultVoice(["fr-FR", "fr-CA"]);
// Get the best voice from a pre-filtered voice list
const customVoice = await voiceManager.getDefaultVoice(["en-US", "en-GB"], customVoiceList);
The selection algorithm:
null if no voices match or if languages parameter is emptyvoiceManager.filterVoices(options: VoiceFilterOptions, voices?: ReadiumSpeechVoice[]): ReadiumSpeechVoice[]
Filters voices based on the specified criteria. If no voices are provided, it filters the instance’s internal voice list.
voiceManager.groupVoices(groupBy: "languages" | "region" | "gender" | "quality" | "provider", voices?: ReadiumSpeechVoice[]): VoiceGroup
Organizes voices into groups based on the specified criteria. The available grouping options are:
"languages": Groups voices by their language code"region": Groups voices by their region"gender": Groups voices by gender"quality": Groups voices by quality level"provider": Groups voices by their providerIf no voices are provided, it groups the instance’s internal voice list.
The library provides opinionated voice sorting capabilities to help you find the best voice for your needs.
If you need more control over the sorting process, you can implement and apply your own sorting logic on filtered voices.
Sort voices from highest to lowest quality:
async voiceManager.sortVoicesByQuality(voices?: ReadiumSpeechVoice[]): Promise<ReadiumSpeechVoice[]>;
// Returns: [veryHigh, high, normal, low, veryLow, null]
If no voices are provided, it sorts the instance’s internal voice list.
Prioritize specific languages while maintaining JSON data’s quality order within each language group:
async voiceManager.sortVoicesByLanguages(preferredLanguages?: string[], voices?: ReadiumSpeechVoice[]): Promise<ReadiumSpeechVoice[]>;
// Returns: [preferred languages voices, other languages voices...]
If no voices are provided, it sorts the instance’s internal voice list.
Sort voices by preferred languages and regions, while maintaining JSON data’s quality order within each region group:
async voiceManager.sortVoicesByRegions(preferredLanguages?: string[], voices?: ReadiumSpeechVoice[]): Promise<ReadiumSpeechVoice[]>;
// Returns: [languages in preferred then alphabetical order → regions: preferred regions → default region → alphabetical regions → voice quality within each region]
If no voices are provided, it sorts the instance’s internal voice list.
voiceManager.convertToSpeechSynthesisVoice(voice: ReadiumSpeechVoice): SpeechSynthesisVoice | undefined
The browser’s SpeechSynthesisVoice for voice, matched by voiceURI, then by the browser’s name (originalName), then by name ignoring case, parentheses and punctuation. undefined when the browser doesn’t have it.
const utterance = new SpeechSynthesisUtterance(text);
const nativeVoice = voiceManager.convertToSpeechSynthesisVoice(voice);
if (nativeVoice) {
utterance.voice = nativeVoice;
utterance.lang = nativeVoice.lang;
}
speechSynthesis.speak(utterance);
voiceManager.getTestUtterance(language: string): string
Retrieves a sample text string suitable for testing text-to-speech functionality in the specified language. If no sample text is available for the specified language, it returns an empty string.
Exported functions that work without a WebSpeechVoiceManager instance.
filterByLanguages(voices: ReadiumSpeechVoice[], languages: string | string[]): ReadiumSpeechVoice[]
filterOutNoveltyVoices(voices: ReadiumSpeechVoice[]): ReadiumSpeechVoice[]
filterOutVeryLowQualityVoices(voices: ReadiumSpeechVoice[]): ReadiumSpeechVoice[]
filterByBoundarySupport(voices: ReadiumSpeechVoice[], needsBoundary: boolean): ReadiumSpeechVoice[]
isNoveltyVoice(voiceName: string, voiceId?: string): boolean
isVeryLowQualityVoice(voiceName: string, quality?: TQuality): boolean
filterByLanguages: matches language or altLanguage, exactly or by base language ("en" and "en-US" both keep "en-GB").filterOutNoveltyVoices / isNoveltyVoice: novelty.json, plus voices flagged isNovelty.filterOutVeryLowQualityVoices / isVeryLowQualityVoice: veryLowQuality.json, plus voices with quality: "veryLow".filterByBoundarySupport: a voice supports boundaries unless controls.boundary === false. Returns the full list when nothing matches.async sortVoicesByRegions(preferredLanguages: string[], voices: ReadiumSpeechVoice[]): Promise<ReadiumSpeechVoice[]>
async pickBestVoiceByRegion(language: string, voices: ReadiumSpeechVoice[]): Promise<ReadiumSpeechVoice | null>
sortVoicesByRegions returns a new array, in the same order as voiceManager.sortVoicesByRegions(). pickBestVoiceByRegion returns what would come first in sortVoicesByRegions([language], voices), without sorting the whole list.
Lower-level building blocks:
async sortByPreferredRegion(voices, processedLang: { baseLang: string; regions: string[] }, jsonOrderMaps?): Promise<void>
async sortAlphabetically(voices, jsonOrderMaps?): Promise<void>
compareByPreferredRegion(a, b, processedLang, jsonOrderMaps): number
compareAlphabetically(a, b, jsonOrderMaps): number
sortByQuality(a, b, jsonOrderMaps?, baseLang?): number
groupVoicesByLanguage(voices, processedLangs): { voicesByLang: Map<string, ReadiumSpeechVoice[]>; otherLangVoices: ReadiumSpeechVoice[] }
async createJsonOrderMap(voices): Promise<Map<string, Map<string, number>>>
getQualityValue(quality): number
sortByPreferredRegion and sortAlphabetically sort in place.sortByQuality is a comparator, not a sort. For two "json" voices listed in jsonOrderMaps under baseLang, their JSON order wins; otherwise higher quality first, then name.createJsonOrderMap: base language → voice name → index in that language’s JSON data, for "json" voices only. Built automatically when omitted.getQualityValue: veryLow 1 … veryHigh 5, 0 when missing or unknown.async pickLanguageVoice(language: string, voices: ReadiumSpeechVoice[], needsBoundary?: boolean): Promise<ReadiumSpeechVoice | null>
async pickDefaultVoice(languages: string[] | undefined, voices: ReadiumSpeechVoice[]): Promise<ReadiumSpeechVoice | null>
pickLanguageVoice picks the voice for language: among the voices of its base language, whatever the region, without novelty or very low quality ones, preferring those whose boundary support is needsBoundary (default true), ranked by pickBestVoiceByRegion: language’s region, then the language’s default region from the JSON, then the others. null without a voice of the language.
pickDefaultVoice picks one voice for several languages: the pickLanguageVoice of the first of languages with one, else the first of sortVoicesByRegions(languages, voices). Without languages, the user’s preferred languages (navigator.languages) are used. voiceManager.getDefaultVoice() differs: it ranks all voices by languages, without preferring boundary events.
extractLangRegionFromBCP47(lang: string): [string, string | undefined]
valueForLanguage<T>(valuesByLanguage: Record<string, T>, lang: string): T | undefined
getLanguageDisplayName(code: string, localization?: string): string
chineseVariantMap: { [key: string]: string }
extractLangRegionFromBCP47: "en-us" → ["en", "US"], "fr" → ["fr", undefined]; _ is read as -. Same as WebSpeechVoiceManager.extractLangRegionFromBCP47().valueForLanguage: the value for the exact tag, else for its primary subtag, keys matched case-insensitively — how the languageOverrides preference is matched. valueForLanguage({ en: "a", "en-GB": "b" }, "en-US") → "a".getLanguageDisplayName: the Intl.DisplayNames name of code, in localization or the runtime’s locale: getLanguageDisplayName("fr", "de") → "Französisch". Falls back to code uppercased.chineseVariantMap: Chinese tags to the language codes of the voice data (cmn.json, yue.json, wuu.json): zh/zh-CN → cmn/cmn-CN, zh-TW → cmn-TW, zh-HK → yue-HK.ReadiumSpeechVoiceinterface ReadiumSpeechVoice {
source: TSource; // "json" | "browser"
// Core identification (required)
label: string; // Human-friendly label for the voice
name: string; // JSON Name (or Web Speech API name if not found)
originalName: string; // Original name of the voice
voiceURI?: string; // For Web Speech API compatibility
// Localization
language: string; // BCP-47 language tag
localizedName?: TLocalizedName; // Localization pattern (android/apple)
altNames?: string[]; // Alternative names (mostly for Apple voices)
altLanguage?: string; // Alternative BCP-47 language tag
otherLanguages?: string[]; // Other languages this voice can speak
multiLingual?: boolean; // If voice can handle multiple languages
// Voice characteristics
gender?: TGender; // Voice gender ("female" | "male" | "neutral")
children?: boolean; // If this is a children's voice
// Quality and capabilities
quality?: TQuality; // This voice's quality, see Quality above
controls?: TServerVoiceControls; // Which playback controls this voice actually honors
// Performance settings
pitch?: number; // Current pitch (0-2, where 1 is normal)
rate?: number; // Speech rate (0.1-10, where 1 is normal)
// Platform and compatibility
browser?: string[]; // Supported browsers
os?: string[]; // Supported operating systems
preloaded?: boolean; // If the voice is preloaded on the system
nativeID?: string | string[]; // Platform-specific voice ID(s)
// Additional metadata
note?: string; // Additional notes about the voice
provider?: string; // Voice provider (e.g., "Microsoft", "Google")
// Allow any additional properties that might be in the JSON
[key: string]: any;
}
LanguageInfointerface LanguageInfo {
code: string;
label: string;
count: number;
}
TQualitytype TQuality = null | "veryLow" | "low" | "normal" | "high" | "veryHigh";
TGendertype TGender = "female" | "male" | "neutral";
TSourcetype TSource = "json" | "browser";
TServerVoiceControlsinterface TServerVoiceControls {
pitch?: boolean;
speed?: boolean;
ssml?: boolean;
boundary?: boolean;
}
The speech server’s GET /service always sends every field explicitly. Client code reading a controls object that might be partial should still treat boundary as enabled when absent and pitch/speed/ssml as unsupported when absent.
TVoiceControlstype TVoiceControls = Pick<TServerVoiceControls, "pitch" | "boundary">;
Used for json/browser voices, where both properties default to enabled when absent. Browser voices, those missing from the JSON, always have boundary: false.