【发布时间】:2016-06-30 10:28:37
【问题描述】:
目前,我正在制作一个使用语音合成 API 朗读文本的简单应用。我想在说话时突出显示单词(粗体)。我目前有一个非常基本的实现,使用 'onboundary' 事件。但是,我想知道是否有更好/更好的方法,因为我的实现是基于一些假设。
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++;
}
}
【问题讨论】:
标签: javascript html speech-synthesis