one
Version:
One is a React framework for web, iOS, and Android apps.
79 lines (76 loc) • 2.11 kB
JavaScript
import { assertSpeakOptions, assertSpeakText } from "./validate.mjs";
function synthesis() {
if (typeof window === "undefined") return void 0;
const candidate = window.speechSynthesis;
return candidate && typeof candidate.speak === "function" ? candidate : void 0;
}
function readMaxInputLength() {
return synthesis() ? 32767 : 0;
}
function findVoice(synth, name) {
return synth.getVoices().find((voice) => voice.voiceURI === name || voice.name === name);
}
function toVoice(voice) {
return {
identifier: voice.voiceURI,
language: voice.lang,
name: voice.name,
quality: "default"
};
}
function speak(text, options) {
assertSpeakText(text);
assertSpeakOptions(options);
const synth = synthesis();
if (!synth) return;
const utterance = new SpeechSynthesisUtterance(text);
if (options?.language !== void 0) utterance.lang = options.language;
if (options?.pitch !== void 0) utterance.pitch = options.pitch;
if (options?.rate !== void 0) utterance.rate = options.rate;
if (options?.volume !== void 0) utterance.volume = options.volume;
if (options?.voice !== void 0) {
const voice = findVoice(synth, options.voice);
if (voice) utterance.voice = voice;
}
utterance.onstart = () => options?.onStart?.();
utterance.onend = () => options?.onDone?.();
utterance.onerror = (event) => {
if (event.error === "canceled") {
options?.onStopped?.();
return;
}
options?.onError?.(new Error(`SpeechSynthesis.speak: ${event.error}`));
};
synth.speak(utterance);
}
async function stop() {
synthesis()?.cancel();
}
async function pause() {
synthesis()?.pause();
}
async function resume() {
synthesis()?.resume();
}
async function isSpeaking() {
const synth = synthesis();
return synth ? synth.speaking : false;
}
async function getAvailableVoices() {
const synth = synthesis();
if (!synth) return [];
return synth.getVoices().map(toVoice);
}
const SpeechSynthesis = Object.freeze({
get maxInputLength() {
return readMaxInputLength();
},
speak,
stop,
pause,
resume,
isSpeaking,
getAvailableVoices
});
export { SpeechSynthesis };
//# sourceMappingURL=index.mjs.map