Angular2: Web Speech API - Voice recognition

2019-04-04 19:22发布

问题:

After reading the documentation of webkitSpeechRecognition (voice recognition in Javascript) I tried to implement it in Angular 2.

But when I did this:

const recognition = new webkitSpeechRecognition();

TypeScript say this error:

[ts] Cannot find name 'webkitSpeechRecognition'. any

And if I try to extract webkitSpeechRecognition from window:

if ('webkitSpeechRecognition' in window) {

    console.log("Enters inside the condition"); // => It's printing

    const { webkitSpeechRecognition } = window; // => TypeScript Error
    const recognition = new webkitSpeechRecognition();
}

If I comment the last two lines the console.log is printed, enters to the condition! webkitSpeechRecognition exists inside window!! But if not comment the last two lines the TypeScript error now is this:

[ts] Type 'Window' has no property 'webkitSpeechRecognition' and no string index signature.
const webkitSpeechRecognition: any

How can I create a new recognition in Angular 2? Has anybody tried it?

回答1:

Finally I solved creating an interface!!

export interface IWindow extends Window {
  webkitSpeechRecognition: any;
}

And:

const {webkitSpeechRecognition} : IWindow = <IWindow>window;
const recognition = new webkitSpeechRecognition();


回答2:

You can solve the problem by

const speechRecognition = Window['webkitSpeechRecognition'];

Or if You are using jQuery

const sr = $(window).get(0).webkitSpeechRecognition;