I am using a modified code snippet from one of the mdn examples. Is there anyway we can make this code return one of the words from phrases exclusively and not any other words. Any alternatives would be appreciated too, if this is not possible.
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList;
var SpeechRecognitionEvent =
SpeechRecognitionEvent || webkitSpeechRecognitionEvent;
var resultPara = document.querySelector(".result");
var testBtn = document.querySelector("button");
const phrases = ["dummy phrase"];
function testSpeech() {
testBtn.disabled = true;
testBtn.textContent = "Listening";
// To ensure case consistency while checking with the returned output text
resultPara.textContent = "";
var recognition = new SpeechRecognition();
var speechRecognitionList = new SpeechGrammarList();
phrases.forEach((phrase) => {
const grammar =
"#JSGF V1.0; grammar phrase; public <phrase> = " + phrase + ";";
speechRecognitionList.addFromString(grammar, 1);
});
recognition.grammars = speechRecognitionList;
recognition.lang = "en-US";
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.start();
recognition.onresult = function (event) {
var speechResult = event.results[0][0].transcript.toLowerCase();
console.log("Speech received: " + speechResult + ".");
resultPara.textContent = speechResult;
console.log("Confidence: " + event.results[0][0].confidence);
};
recognition.onspeechend = function () {
recognition.stop();
testBtn.disabled = false;
testBtn.textContent = "Start new test";
};
recognition.onerror = function (event) {
testBtn.disabled = false;
testBtn.textContent = "Start new test";
console.error("Error occurred in recognition: " + event.error);
};
}
testBtn.addEventListener("click", testSpeech);