bocko
bocko

Reputation: 398

How to stop TextToSpeech in Ionic 2

I am having trouble stopping the playback of Ionic TextToSpeech. Here is the function that I am calling:

...
speaking : boolean = false;
...

sayText(txt:string, loc: string){

  if (this.speaking){
     this.tts.stop();  // <<< does not seem to work?
     this.speaking = false;
     return;
  }
  this.speaking = true;
  this.tts.speak( {text: txt, locale: loc} )
    .then((val) => { this.speaking = false;  },
          (reject) => {console.warn(reject); this.speaking = false; })
    .catch((err) => {console.error(err); this.speaking = false; });
}

This starts the speech just fine, but if it's called again during the playback it does not stop the playback...

I have injected tts: TextToSpeech in constructor, and of course imported the declaration at the beginnning:

import { TextToSpeech } from '@ionic-native/text-to-speech';

Am I missing something? Thanks.

Upvotes: 0

Views: 1183

Answers (1)

Soyab Shaikh
Soyab Shaikh

Reputation: 144

call tts.speak with an empty string to interrupt.

sayText(txt:string, loc: string){
  if(this.speaking){
    this.tts.speak({text: ''});  // <<< speak an empty string to interrupt.
    this.speaking = false;
    return;
  }
  this.speaking = true;
  this.tts.speak( {text: txt, locale: loc} )
 .then((val) => { this.speaking = false;  },
 (reject) => {console.warn(reject); this.speaking = false; })
 .catch((err) => {console.error(err); this.speaking = false; });
}

Upvotes: 2

Related Questions