Currently, I'm making a simple app where text is spoken using the speech synthesis API. I want to highlight the words (bold) as they are being spoken. I currently have a very basic implementation doing this using the 'onboundary' event. However, I'm wondering if there's a better/nicer way of doing it, as my implementation is based on a few presumptions.
var words;
var wordIdx;
var text;
var utterance = new SpeechSynthesisUtterance();
utterance.lang = 'en-UK';
utterance.rate = 1;
window.onload = function(){
document.getElementById('textarea').innerText = 'This is a text area. It is used as a simple test to check whether these words are highlighted as they are spoken using the web speech synthesis API (utterance).';
document.getElementById('playbtn').onclick = function(){
text = document.getElementById('textarea').innerText;
words = text.split(' ');
wordIdx = 0;
utterance.text = text;
speechSynthesis.speak(utterance);
}
utterance.onboundary = function(event){
var e = document.getElementById('textarea');
var it = '';
for(var i = 0; i < words.length; i++){
if(i === wordIdx){
it += '<strong>' + words[i] + '</strong>';
} else {
it += words[i];
}
it += ' ';
}
e.innerHTML = it;
wordIdx++;
}
}