Search code examples
iosiphoneobjective-cios7text-to-speech

How to stop the voice during text-to-speech synthesis?


I used the following code to initial the text to speech synthesis using a button. But sometimes users may want to stop the voice in the middle of the speech. May i know is there any code i can do that.

Thanks

Here is my code

@interface RMDemoStepViewController ()

@end

@implementation RMDemoStepViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    //Add Border to TextBox


    //Instantiate the object that will allow us to use text to speech
    self.speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
    [self.speechSynthesizer setDelegate:self];

}
- (IBAction)speakButtonWasPressed:(id)sender{

    [self speakText:[self.textView text]];

}

- (void)speakText:(NSString *)toBeSpoken{

    AVSpeechUtterance *utt = [AVSpeechUtterance speechUtteranceWithString:toBeSpoken];
    utt.rate = [self.speedSlider value];
    [self.speechSynthesizer speakUtterance:utt];

}

- (IBAction)speechSpeedShouldChange:(id)sender
{
    UISlider *slider = (UISlider *)sender;
    NSInteger val = lround(slider.value);
    NSLog(@"%@",[NSString stringWithFormat:@"%ld",(long)val]);
}
@end

Solution

  • But sometimes users may want to stop the voice in the middle of the speech.

    To stop speech, send the speech synthesizer a -stopSpeakingAtBoundary: message:

    [self.speechSynthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    

    Use AVSpeechBoundaryWord instead of AVSpeechBoundaryImmediate if you want the speech to continue to the end of the current word rather than stopping instantly.

    You can also pause speech instead of stopping it altogether.