微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么每次运行时相同的语音识别代码都会有不同的表现?

如何解决为什么每次运行时相同的语音识别代码都会有不同的表现?

这是我的代码

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//
  }
}

这里的问题是我无法从cust_response(response)调用voice_recognition.onresult函数

编辑: 我已经将这个voice_recognition.onresult = function(event){}更改为voice_recognition.addEventListener(“ result”,(event)=> {}),并且正在其中调用函数。但是通过此更改,有时会调用voice_recognition.addEventListener(“ result”,(event)=> {}),当我再次运行时,它不会调用函数,甚至不会执行voice_recognition.addEventListener(“ error”,(event)= > {})。为什么相同的代码有时会运行,而其他时间却没有运行?

解决方法

您需要使用bind(this)或箭头函数符号在回调中使用this关键字访问类成员变量。

尝试以下

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();
  }
}

您可以参考here以获得更多详细信息。

,

通过使用function关键字,您没有将上下文(this)绑定到该函数。

您应该:

  • (首选)使用箭头功能,它将绑定上下文 例如:
voice_recognition.onresult = (e) => {
  ...
  this.cust_response(response);
}
  • 在封闭范围内捕获this变量,并引用该变量 例如:
const self = this;

voice_recognition.onresult = function(e){
  ...
  self.cust_response(response);
}

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。