I am having issues with receiving and storing voice input using the JavaScript Speech Recognition API. I followed some tutorials and set up everything correctly and got the code to work just fine. Then I decided to create a class called AI that could store the most recent input, and eventually add some sort of speech parsing methods. But when I put the recognition.onresult function within the class, the voice commands were not stored into the ai.recentCommand variable. Instead it would just print "none". Here is what I have so far.
class AI {
constructor() {
this.recentCommand = "none";
this.recognition = new webkitSpeechRecognition();
this.recognition.lang = 'en-US';
this.recognition.interimResults = false;
this.recognition.maxAlternatives = 5;
}
getInput() {
this.recognition.onresult = function(event) {
this.recentCommand = event.results[0][0].transcript;}
this.recognition.start();
}
}
var button = document.getElementById("button");
var output = document.getElementById("output");
var ai = new AI();
// Gets input fine, but I want to use the getInput() method instead
ai.recognition.onresult = function(event) {
ai.recentCommand = event.results[0][0].transcript;
}
ai.recognition.start();
// I want to get the input through the ai.getInput() method, but isn't working
ai.getInput();
button.addEventListener("click", function() {output.innerHTML =
ai.recentCommand});
Does it have something to do with a function being within a function? Any help would be greatly appreciated. Thanks in advance.