import { Injectable , Inject } from '@angular/core' ; import { Observable } from 'rxjs/Observable' ; const SpeechRecognition = window && ( ( < any > window ) . SpeechRecognition || ( < any > window ) . webkitSpeechRecognition || ( < any > window ) . mozSpeechRecognition || ( < any > window ) . msSpeechRecogntion ) ; @ Injectable ( ) export class SpeechService { constructor ( ) { } listen ( ) { return new Observable < string [ ] > ( observer => { const speech = new SpeechRecognition ( ) ; const resultHandler = ( e ) => { console . log ( e ) ; const results = this . cleanSpeechResults ( e . results ) ; observer . next ( results ) ; observer . complete ( ) ; } ; const errorHandler = ( err ) => { observer . error ( err ) ; } ; speech . addEventListener ( 'result' , resultHandler ) ; speech . addEventListener ( 'error' , errorHandler ) ; speech . start ( ) ; return ( ) => { speech . removeEventListener ( 'result' , resultHandler ) ; speech . removeEventListener ( 'error' , errorHandler ) ; speech . abort ( ) ; } ; } ) ; } private cleanSpeechResults ( results ) { return < string [ ] > ( Array . from ( results ) . reduce ( ( final , result ) => final . concat ( Array . from ( result , ( x ) => x . transcript ) ) , [ ] ) ) ; } }