Text to Speech (TTS) is a new feature in iOS7. Text to Speech, as the phrase implies, converts a text to speech. By default, the voice is an American female. And it is a bit too fast. So, I wrote a small helper class to adjust the TTS experience. The helper class, TTSHelper, uses a British male voice. And it speaks a bit slower.

TTS Helper

The code for the helper class is shown below.

@implementation TTSHelper

-(id)init
{
    voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-GB"];
    speech = [[AVSpeechSynthesizer alloc] init];
    return self;
}

-(void)speakText:(NSString *)text
{
    AVSpeechUtterance *welcome = [[AVSpeechUtterance alloc] initWithString:text];
    welcome.rate = 0.35;
    welcome.voice = voice;
    [speech speakUtterance:welcome];
}
@end

There are three classes in Objective-C to control the TTS experience.

  1. AVSpeechSynthesisVoice
  2. AVSpeechUtterance
  3. AVSpeechSynthesizer

Constructor

TTSHelper class has a constructor and the speakText method. The constructor initialises the voice and speech objects.AVSpeechSynthesisVoice is the class that abstracts the voice. It has a static method, voiceWithLanguage. The en-GB value for the voice sets a British male english voice. For the speech object, initialise the AVSpeechSynthesizer class.

Speech method

TTSHelper class has the speakText method which converts text to speech. AVSpeechUtterance class provides the input to the speech object. It has the following properties to control how the text is spoken.

  • Text: Text to speak.
  • Rate: Pace of the voice.
  • Voice: AVSpeechSynthesisVoice object

For our example, the rate of utterance is set to 0.35. Which is a bit slower than the default.

Finally, the AVSpeechSynthesizer object does the actual speaking. It has the speakUtterance method which takes in an utterance and converts it to speech.

As you can see, AVSpeechSynthesizer object uses the AVSpeechUtterance object. And AVSpeechUtterance object uses the AVSpeechSynthesisVoice object.

Related Posts

Leave a Reply

Your email address will not be published.