Search code examples
angularinterfacewindowangular2-servicesspeech-synthesis

Trying to use speechSynthesis in Angular2 with IWindow Interface


I'm trying to use the speechSynthesis http://blog.teamtreehouse.com/getting-started-speech-synthesis-api

First I extended the window with an interface:

window.interface.ts

export interface IWindow extends Window {
  webkitSpeechRecognition: any;
  speechSynthesis: any;
}

Next I made a window service:

window.service.ts

import { Injectable } from '@angular/core';
import { IWindow } from '../interfaces/window-interface';

function _window() : IWindow {
   return window;
}
@Injectable()
export class WindowService {
   get nativeWindow() : any {
      return _window();
   }
}

Now in the component, I'm trying to implement it.... without success..

app.component

import { Component, OnInit, ViewChild } from '@angular/core';
import { WindowService } from '../../providers/window.service';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['.app.component.scss']
})
export class AppComponent implements OnInit {
   constructor(private _router: Router, private _window: WindowService ) { }

   sayIt() {
      var utterance = new SpeechSynthesisUtterance('Hello World');
      this._window.speechSynthesis.speak(utterance);
   }
}

TS Error:

Cannot find name 'SpeechSynthesisUtterance'.)
Property 'speechSynthesis' does not exist on type 'WindowService'.)

I used this article on speech recognition as a reference also: Angular2: Web Speech API - Voice recognition

Still getting error -- Property 'speechSynthesis' does not exist on type 'Window'


Solution

  • It can be done as below

     var msg = new SpeechSynthesisUtterance("hello world");
     (<any>window).speechSynthesis.speak(msg)
    

    Got help from the link

    SpeechRecognition and SpeechSynthesis in TypeScript