简体   繁体   中英

Why is the same Speech Recognition code behaving differently every time i run?

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?

You either need to use bind(this) or arrow function notation to access class member variables using this keyword in callbacks.

Try the following

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 = (e) => {              // <-- arrow function
    const repsonse = e.results[0][0].transcript;
    this.cust_response(response);
    voice_recognition.stop();
  }

  voice_recognition.onerror = (e) => {
    voice_recognition.stop();
  }
}

You could refer here for more details.

By using the function keyword, you are not binding a context ( this ) to the function.

You should either:

  • (preferred) Use an arrow function, which will bind the context Eg:
voice_recognition.onresult = (e) => {
  ...
  this.cust_response(response);
}
  • Capture the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM