我将从Webkit语音识别中获取文本,并且在HTML中有一个段落,我想将从语音识别中获取的文本与我的段落进行匹配,并突出显示该段落的文本。
var message = document.querySelector('#message');
var text = document.querySelector('#text').innerHTML;
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList;
var grammar = '#JSGF V1.0;'
var recognition = new SpeechRecognition();
var speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.onresult = function(event) {
var last = event.results.length - 1;
var command = event.results[last][0].transcript;
message.textContent = 'Voice Input: ' + command + '.';
if (command.length !== 0) {
//Handle special characters used in regex
var searchregexp = new RegExp(command.replace(/[.*+?^${}()|[\]\\]/, '\\$&'));
//$& will maintain uppercase and lowercase characters.
$(this).html($(this).html().toLowerCase().replace(searchregexp, "<span class = 'highlight'>$&</span>"));
}
};
recognition.onspeechend = function() {
recognition.stop();
};
recognition.onerror = function(event) {
message.textContent = 'Error occurred in recognition: ' + event.error;
}
document.querySelector('#btnGiveCommand').addEventListener('click', function(){
recognition.start();
});