Sometimes, we want to use JavaScript speech synthesis with longer texts.
In this article, we’ll look at how to use JavaScript speech synthesis with longer texts.
Use JavaScript Speech Synthesis with Longer Texts
To use JavaScript speech synthesis with longer texts, we can create a function to resume the utterance of the text.
Then we can resume the utterance when the start event is emitted.
For instance, we can write:
const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
const utterance = new SpeechSynthesisUtterance(text);
window.speechSynthesis.speak(utterance);
const resumeInfinity = () => {
window.speechSynthesis.resume();
timeoutResumeInfinity = setTimeout(resumeInfinity, 1000);
}
utterance.onstart = (event) => {
resumeInfinity();
};
utterance.onend = (event) => {
clearTimeout(timeoutResumeInfinity);
};
We speak the text
with:
const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
const utterance = new SpeechSynthesisUtterance(text);
window.speechSynthesis.speak(utterance);
Then we create the resumeInfinity
function which calls window.speechSynthesis.resume
to continue speaking the text.
Then we create the timeoutResumeInfinity
timer to call resumeInfinity
after 1 second.
We call resumeInfinity
in the onstart
method so that the text is spoken until it reaches the end.
And in the onend
method, we call clearTimeout
with timeoutResumeInfinity
to clear the timer.
Conclusion
To use JavaScript speech synthesis with longer texts, we can create a function to resume the utterance of the text.
Then we can resume the utterance when the start event is emitted.