Web Speech API
Demo detecting words
by kmturley
HTML
<div class="output" id="output">Say something...</div>
CSS
html,
body {
height: 100%;
margin: 0;
overflow: hidden;
}
body {
background-color: #fff;
box-sizing: border-box;
color: #333;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: normal;
font-size: 3rem;
padding: 2rem;
position: relative;
}
.output {
color: #000;
bottom: 2rem;
position: absolute;
}
.output span {
color: #6195ED;
}
JavaScript
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition,
recognition = new SpeechRecognition(),
output = document.getElementById('output');
recognition.continuous = true;
recognition.interimResults = true;
recognition.start();
recognition.onstart = function(e) {
console.log('onstart', e);
};
recognition.onend = function(e) {
console.log('onend', e);
};
recognition.onresult = function(e) {
console.log('onresult', e);
if (typeof(e.results) == 'undefined') {
console.log('onresult restart');
recognition.stop();
recognition.start();
return;
}
generate(e.results);
};
recognition.onspeechend = function(e) {
console.log('onspeechend', e);
};
recognition.onerror = function(e) {
console.log('onerror', e);
};
function generate(items) {
var i = 0,
html = '';
for (i = 0; i < items.length; i += 1) {
if (check(items[i][0].transcript)) {
html += '<span>' + items[i][0].transcript + '</span>';
} else {
html += items[i][0].transcript;
}
}
output.innerHTML = html;
};
function check(text) {
if (text.indexOf('weather') !== -1) {
console.log('weather');
return true;
} else {
return false;
}
}