xxxxxxxxxx
86
var SpeechRecognition = window.SpeechRecognition || webkitSpeechRecognition;
var SpeechGrammarList = window.SpeechGrammarList || webkitSpeechGrammarList;
var SpeechRecognitionEvent = window.SpeechRecognitionEvent || webkitSpeechRecognitionEvent;
var colors = [ 'aqua' , 'azure' , 'beige', 'bisque', 'red', 'green', 'black', 'blue', 'brown', 'chocolate', 'coral'];
var grammar = '#JSGF V1.0; grammar colors; public <color> = ' + colors.join(' | ') + ' ;';
var recognition = new SpeechRecognition();
var speechRecognitionList = new SpeechGrammarList();
var state = false;
var button;
var result_text = 'got result: ';
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (search instanceof RegExp) {
throw TypeError('first argument must not be a RegExp');
}
if (start === undefined) { start = 0; }
return this.indexOf(search, start) !== -1;
};
}
String.prototype.contains = function(words) {
let result = [];
for (let i = 0; i < words.length; i++) {
let word = words[i];
if (this.indexOf(word, 0) !== -1) result.push(i);
}
if (result.length == 0) result = null;
return result;
}
function setup() {
createCanvas(windowWidth, windowHeight);
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
recognition.continuous = false;
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
button = createButton('click me');
button.position(0, 0);
button.mousePressed(toggleSpeech);
recognition.onresult = function(event) {
var color = event.results[0][0].transcript;
result_text = `got result: ${color}`;
console.log(result_text);
}
}
function toggleSpeech() {
if (state == false) {
recognition.start();
state = true;
}
else {
recognition.stop();
state = false;
}
}
function draw() {
background(220);
textAlign(CENTER, CENTER);
textSize(32);
text(result_text, width/2, height/2)
let ids = result_text.contains(colors);
if (ids != null) {
let ctext = '';
for (let i of ids) {
ctext += colors[i] + ' ';
}
text(`the text includes the colours ${ctext}`, width/2, height/2 + 64)
}
}