Here is my code
export class recognition {
constructor() { }
public startrecognition() {
const voice_recognition = new webkitSpeechRecognition();
voice_recognition.continuous = false;
voice_recognition.interimresults = false;
voice_recognition.lang = "en-US";
voice_recognition.start();
voice_recognition.onresult = function (e) {
const repsonse = e.results[0][0].transcript;
this.cust_response(response);
voice_recognition.stop();
}
voice_recognition.onerror = function (e) {
voice_recognition.stop();
}
}
public cust_response(response) {
//Some code here using response given by customer//
}
}
The problem here is I'm unable to call the cust_response(response)
function from voice_recognition.onresult
.
Edit: I have changed this voice_recognition.onresult=function(event){} to voice_recognition.addEventListener("result",(event)=>{}) and this was calling the function inside it. But with this change it sometimes calling voice_recognition.addEventListener("result",(event)=>{}) and when i run again its not calling this function and even it's not executing voice_recognition.addEventListener("error",(event)=>{}). Why is the same code running sometimes and not running the other times?
By using the function
keyword, you are not binding a context (this
) to the function.
You should either:
voice_recognition.onresult = (e) => {
...
this.cust_response(response);
}
this
variable in the enclosing scope and refer to that
Eg:const self = this;
voice_recognition.onresult = function(e){
...
self.cust_response(response);
}
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this