import { Inject , Injectable } from '@angular/core' ; import { BrowserFeatureKey , FeatureService , WINDOW } from '@ngx-starter-kit/core' ; const SpeechRecognition = ( window as any ) . webkitSpeechRecognition || ( window as any ) . mozSpeechRecognition || ( window as any ) . msSpeechRecognition || ( window as any ) . oSpeechRecognition || ( window as any ) . SpeechRecognition ; dynamic @ Injectable ( ) export class SpeechToTextService { public canUseSpeechRecognition = false ; private speechRecognition : any ; constructor ( private readonly featureService , @ Inject ( WINDOW ) private window ) { this . canUseSpeechRecognition = this . featureService . detectFeature ( BrowserFeatureKey . SpeechRecognition ) . supported ; if ( this . canUseSpeechRecognition ) { this . speechRecognition = new SpeechRecognition ( ) ; this . speechRecognition . continuous = false ; this . speechRecognition . lang = 'en-US' ; this . speechRecognition . interimResults = false ; this . speechRecognition . maxAlternatives = 1 ; } } public getVoiceMessage ( ) { return new Promise ( ( resolve , reject ) : void => { this . speechRecognition . onresult = ( speech ) : void => { let sentence = '' ; if ( speech . results ) { const result = speech . results [ speech . resultIndex ] ; const transcript = result [ 0 ] . transcript ; if ( result . isFinal ) { if ( result [ 0 ] . confidence < 0.1 ) { console . log ( 'Unrecognized result - Please try again' ) ; } else { sentence = transcript . trim ( ) ; console . log ( `Sentence: ${ sentence }` ) ; console . log ( `Confidence: ${ result [ 0 ] . confidence }` ) ; resolve ( sentence ) ; } } } } ; this . speechRecognition . onspeechend = ( ev ) : void => { this . speechRecognition . stop ( ) ; } ; this . speechRecognition . onnomatch = ( err ) : void => { console . log ( 'No Match' ) ; reject ( 'I didn\'t recognise your question.' ) ; } ; this . speechRecognition . onerror = ( err ) : void => { console . log ( 'Error: ' + err . error ) ; reject ( err . error ) ; } ; this . speechRecognition . start ( ) ; } ) ; } }