What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet:

export class voiceRecognition {
  constructor() { }

  public startVoiceRecognition() {
    const recognition = new webkitSpeechRecognition();
    recognition.continuous = false;
    recognition.interimresults = false;
    recognition.lang = "en-US";

    recognition.start();

    recognition.onresult = function (e) {
      const response = e.results[0][0].transcript;
      this.customResponse(response);
      recognition.stop();
    }

    recognition.onerror = function (e) {
      recognition.stop();
    }
  }

  public customResponse(response) {
    //Code to handle customer response goes here//
  }
}

The issue I'm facing is I'm having trouble calling the customResponse(response) function from recognition.onresult.

Update: I switched from

recognition.onresult=function(event){}
to
recognition.addEventListener("result",(event)=>{})
and this successfully called the function inside it. However, I'm encountering a problem where sometimes it works and sometimes it doesn't when I run it again. It's not even executing
recognition.addEventListener("error",(event)=>{})
. Any idea why the same code behaves differently at times?

Answer №1

When you use the function keyword, the context (this) is not bound to the function.

There are two ways to address this:

  • (recommended) Use an arrow function, which automatically binds the context. For example:
voice_recognition.onresult = (e) => {
  ...
  this.cust_response(response);
}
  • Alternatively, store the value of this in a variable in the enclosing scope and refer to it. For example:
const self = this;

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

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

Answer №2

To access class member variables using the this keyword in callbacks, you can either use bind(this) or arrow function notation.

Consider implementing the following:

public beginSpeechRecognition() {
  const speechRecognition = new webkitSpeechRecognition();
  speechRecognition.continuous = false;
  speechRecognition.interimresults = false;
  speechRecognition.lang = "en-US";

  speechRecognition.start();

  speechRecognition.onresult = (e) => {              
    const response = e.results[0][0].transcript;
    this.processResponse(response);
    speechRecognition.stop();
  }

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

For more information, you can check out this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The entity is not validated by class-validator

Is it possible to utilize class-validator for validating columns in an Entity? The validation does not seem to work for columns: import { IsEmail } from 'class-validator'; @Entity() export class Admin extends BaseEntity { @Column({ unique: t ...

Obtain the user's ID in string format from the clerk

I'm trying to retrieve the clerk ID to cross-reference with the backend. The issue is that the clerk is using a hook which isn't compatible with this function type. export const getServerSideProps = async ({ req }) => { const { isLoaded, is ...

Having trouble customizing the toolbar on ngx-quill? Quill seems to be having trouble importing modules

UPDATE: I jumped ship when I discovered that PrimeNg had a quill implementation, and since I was already using PrimeNg, I switched over. Initially had some issues, but upgrading to angular 7 and ngrx 7 beta resolved them. https://www.primefaces.org/primeng ...

Expanding external type declarations within Typescript

I am currently working with Typescript and the ant design library. My goal is to extend an existing interface by adding a single property. To start, I imported the original interface so you can see the folder structure: import { CollapseProps } from &apo ...

Error retrieving data from JSON

I'm attempting to extract a value from the JSON data retrieved via Ajax. Take a look at the example I'm working on here: http://jsfiddle.net/NNrcp/6/. jQuery.ajax({ url:"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.pla ...

Guide to testing template-driven forms in Angular 6

Currently, I am working on a template-driven form which looks like this: <form #form="ngForm" (ngSubmit)="onSubmit()"> <input class="form-control input-lg" id="venue_name" name="venue_name" type="text" #venue_name="ngModel" [(n ...

Why is it possible for me to call a function that is defined below a component?

My understanding was that in Javascript, functions could not be invoked if they are defined below where they're called (unless hoisting is involved). However, I discovered something interesting while working with React. The code snippet below actuall ...

The search for d.ts declaration files in the project by 'typeRoots' fails

// Within tsconfig.json under "compilerOptions" "typeRoots": ["./@types", "./node_modules/@types"], // Define custom types for Express Request in {projectRoot}/@types/express/index.d.ts declare global { namespace Express { interface Request { ...

Guide on using automapper in typescript to map a complex object to a "Map" or "Record" interface

I have been utilizing the automapper-ts with typescript plugin for automatic mapping. Check it out here While it works smoothly for simple objects, I encountered issues when dealing with complex ones like: Record<string, any> or Map<string, Anoth ...

Issue with VueJS rendering data within a for loop

As a newcomer to VueJS, I appreciate your patience as I navigate through this. Let me provide as much detail as possible. I am currently working on a Vue app that needs to retrieve a response from a server, iterate through the data, and set a Vue data var ...

Tips for dynamically updating the id value while iterating through a class

Here's the HTML snippet I am working with: <div class="info"> <div class="form-group"> <label class="control-label col-sm-2">Title</label> <div class="col-xs-10 col-sm-8"> <inpu ...

The issue of JQuery selector failure within an AngularJS controller

In my current setup, I have viewA along with ControllerA. However, when an image is clicked on viewA, I need to switch over to another ViewB along with its corresponding ControllerB. In ViewB, there are multiple checkboxes which the user can interact wit ...

What is the process for obtaining the feedback from a new StepFunctionsStartExecution operation using AWS CDK?

Task Explanation: Iterate through the children in Step Function 1 Forward each JSON object to Step Function 2 Upon completion of Step Function 2, a response is obtained from an external API Utilize this API response within Step Function 1 Visual Represen ...

Using Axios to retrieve data from a MySQL database is a common practice in web development. By integrating Vue

I have developed another Vue.js admin page specifically for "writer" where I can display post data fetched from a MySQL database. The admin page called "admin" is functioning properly and responding with all the necessary data. The following code snippet ...

organize the values based on their priority using reactjs

I'm facing a challenge involving two arrays of objects: array1 and array2. I need to display only three values from both arrays, with priority given to array1. The requirements are as follows: if array1 contains 3 elements, all three should be shown. ...

Send information to a different module

I've created a straightforward form component: <template> <div> <form @submit.prevent="addItem"> <input type="text" v-model="text"> <input type="hidden" v-model="id"> <i ...

Restrict HTML Elements Based on Their Size

I have a text file with a substantial amount of content that I need to display in an HTML format. The challenge is that I only want to show a portion of the text on the screen, but I am unsure of the exact amount that needs to be displayed. What I do know ...

How can I ensure security measures are in place to avoid XSS attacks on user-generated HTML content?

Currently, I am in the process of developing a web application that will allow users to upload entire web pages onto my platform. My initial thought was to utilize HTML Purifier from http://htmlpurifier.org/, but I am hesitant because this tool alters the ...

The React namespace is missing the exported member 'InputHTMLAttributes', and the MenuItemProps interface is incorrectly extending the ListItemProps interface

I am currently working with Material-UI and typescript. I have installed the typescript types using npm install -D @types/material-ui. After loading my webpage, I encountered the following errors: ERROR in [at-loader] ./node_modules/@types/material ...

Alert from Webpack regarding a critical dependency in the view.js file of the Express library located in the node_modules directory: an expression is being used

Currently, I'm in the process of working on my inaugural full stack application (a simplistic notepad app) and while bundling webpack, I've encountered an issue that is a cause for concern: WARNING in ./node_modules/express/lib/view.js 81:13-2 ...