voice-tts
Version:
Universal Text-to-Speech voice management library
77 lines • 2.33 kB
JavaScript
export class Voice {
constructor() {
Object.defineProperty(this, "_speechSynthesisVoices", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "targetVoice", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
get speechSynthesisVoices() {
return this._speechSynthesisVoices;
}
async init() {
if (!('speechSynthesis' in window)) {
throw new Error('Web Speech API is not supported');
}
this._speechSynthesisVoices = speechSynthesis.getVoices();
if (this._speechSynthesisVoices.length) {
return;
}
await new Promise((resolve) => {
const handler = () => {
this._speechSynthesisVoices = speechSynthesis.getVoices();
speechSynthesis.removeEventListener('voiceschanged', handler);
resolve();
};
speechSynthesis.addEventListener('voiceschanged', handler);
});
}
change(name) {
if (!this._speechSynthesisVoices.length) {
throw new Error('The list of votes is empty');
}
const found = this._speechSynthesisVoices.find((voice) => voice.name === name);
if (!found) {
throw new Error(`Voice “${name}” not found`);
}
this.targetVoice = found;
}
speak(text) {
if (!this.targetVoice) {
console.warn('No voice selected. Default voice is being used');
}
const utterance = new SpeechSynthesisUtterance(text);
console.log(this.targetVoice);
if (this.targetVoice) {
utterance.voice = this.targetVoice;
utterance.lang = this.targetVoice.lang;
}
speechSynthesis.speak(utterance);
}
pause() {
speechSynthesis.pause();
}
resume() {
speechSynthesis.resume();
}
stop() {
speechSynthesis.cancel();
}
isSpeaking() {
return speechSynthesis.speaking;
}
isPaused() {
return speechSynthesis.paused;
}
isPending() {
return speechSynthesis.pending;
}
}
//# sourceMappingURL=Voice.js.map