Last active
November 29, 2022 18:10
-
-
Save jdgregson/3f21c3e47c7d9a7948bd04888aaf7865 to your computer and use it in GitHub Desktop.
Browser text-to-speach
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
/** | |
* Uses the borwser's speech synthesis API to speak the given text. Example: | |
* | |
* speak('This is a secret mission in uncharted space.', 2, 1, 2); | |
* | |
* @param {string} test The text to speak. | |
* @param {float} rate The rate at which to speak the text, between 0.1 and 10. | |
* @param {float} pitch The pitch at which to speak the text, between 0 and 2. | |
* @param {int} voice The voice to use, e.g. 3. | |
*/ | |
const speak = (text, rate = 1, pitch = 1, voice = 0) => { | |
const textSynth = new SpeechSynthesisUtterance(); | |
const voices = window.speechSynthesis.getVoices(); | |
textSynth.voice = voices[0]; | |
if (voice && voice !== 0 && voices.length >= voice) { | |
textSynth.voice = voices[voice]; | |
} | |
textSynth.rate = 1; | |
if (rate && rate >= 0.1 && rate <= 10) { | |
textSynth.rate = rate; | |
} | |
textSynth.pitch = 1; | |
if (pitch && pitch >= 0 && pitch <= 2) { | |
textSynth.pitch = pitch; | |
} | |
textSynth.text = text; | |
speechSynthesis.speak(textSynth); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment