Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Last active January 23, 2021 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikoheikkila/364236042d45e253c11efbad8df59122 to your computer and use it in GitHub Desktop.
Save nikoheikkila/364236042d45e253c11efbad8df59122 to your computer and use it in GitHub Desktop.
Javascript: Text-to-Speech (TTS) in Browser
class TextToSpeech {
constructor({ volume = 1, rate = 1, pitch = 1, lang = "en" } = {}) {
if (typeof window === 'undefined' || !"speechSynthesis" in window) {
throw new Error("Text to speech is not supported in your browser.");
}
this.engine = new SpeechSynthesisUtterance();
this.setLanguage(lang)
.setPitch(pitch)
.setRate(rate)
.setVolume(volume)
}
speak(text) {
this.setText(text);
window.speechSynthesis.speak(this.engine);
}
mute() {
return this.setVolume(0);
}
unmute() {
return this.setVolume(1);
}
setLanguage(lang) {
this.engine.lang = lang;
return this;
}
setPitch(pitch) {
this.engine.pitch = pitch;
return this;
}
setRate(rate) {
this.engine.rate = rate;
return this;
}
setVolume(volume) {
this.engine.volume = volume;
return this;
}
setText(text) {
this.engine.text = text;
return this;
}
}
const tts = new TextToSpeech();
tts.speak(
"Lemon lime minty coconut açai spiced pumpkin chili bananas dragon fruit red lentil curry shallots plums tabasco"
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment