Last active
January 23, 2021 14:31
-
-
Save nikoheikkila/364236042d45e253c11efbad8df59122 to your computer and use it in GitHub Desktop.
Javascript: Text-to-Speech (TTS) in Browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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