When I got a Mac mini in 2008, one of the coolest things it could do was speaking. That is an accessibility feature, but not being disabled never prevented me from staying hours typing random stuff on terminal just to get to hear the computer talking.

It turns out we developers can use that feature too. And it just takes a few lines of code. Start by opening Xcode and creating a new project.


Screen Shot 2015-06-10 at 7.34.30 AM

Screen Shot 2015-06-10 at 7.34.49 AM

To demonstrate the capatibilities of NSSpeechSynthesizer, we will need a NSTableView, a NSTextField and a button.

Screen Shot 2015-06-13 at 1.40.11 PM
 To get the available voices, we can use the following line:

[NSSpeechSynthesizer availableVoices];

It will return a NSArray of NSStrings which are voice identifiers(e.g. com.apple.speech.synthesis.voice.Bells). To get more information about a voice(e.g. name, age, language, gender), use the following line:

[NSSpeechSynthesizer attributesForVoice:voiceIdentifier];

It will return a NSDictionary. Now lets get the app speaking:

NSSpeechSynthesizer *synthesizer = [[NSSpeechSynthesizer alloc] init];
NSArray *voices = [NSSpeechSynthesizer availableVoices];
NSInteger selectedVoice = [tableViewVoices selectedRow];
NSString *voice = [voices objectAtIndex:selectedVoice];

NSString *text = [textToSpeak stringValue];

[synthesizer setVoice:voice];
[synthesizer startSpeakingString:text];

And that’s it! Just a few lines of code and you can get a cool feature on your app. To download the sample project, click here.