Search code examples
iosxcodeif-statementtext-to-speechavspeechsynthesizer

AVSpeechSynthesizer - If AVSpeechSynthesizer is Speaking & if has stopped speaking


I want to display a view on my app whilst AVSpeechSynthesizer is speaking, and for the view to disappear when it has stopped speaking.

-(void)speakText {
    AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init];
    float speechSpeed = 0.12;
    AVSpeechUtterance *synUtt = [[AVSpeechUtterance alloc] initWithString:textString];
    [synUtt setRate:speechSpeed];
    [synUtt setVoice:[AVSpeechSynthesisVoice voiceWithLanguage:selectedVoice]];
    [synthesizer speakUtterance:synUtt];


//BELOW TO APPEAR AND AND DISAPPEAR

        [UIButton beginAnimations:nil context:nil];
        [UIButton setAnimationDuration:0.5];
        [UIButton setAnimationDelay:0.0];
        [UIButton setAnimationCurve:UIViewAnimationCurveEaseOut];
        _speakingScrollView.frame = CGRectMake(236, 675, _speakingScrollView.frame.size.width, _speakingScrollView.frame.size.height);
        [self.view bringSubviewToFront:_speakingScrollView];
        [UIView commitAnimations];

}

I can't seem to work out out how to go about this? I've seen the apple documentation suggests

@property(nonatomic, readonly, getter=isSpeaking) BOOL speaking

But I can't workout how to implement this into my app.


Solution

  • A quick look at the docs for AVSpeechSynthesizer reveals that it has a delegate property.

    You should set the delegate and implement the AVSpeechSynthesizerDelegate protocol so that you can be notified of events for the speech synthesizer.

    Events such as

    - (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
     didFinishSpeechUtterance:(AVSpeechUtterance *)utterance;
    

    and

    - (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer
      didStartSpeechUtterance:(AVSpeechUtterance *)utterance;
    

    would be most interesting to you, considering you want to know when it starts and stops. There are also events for being canceled, paused, and continued, which you will probably also want to implement to hide and show your UI.