iOS 9 Swift Programming Cookbook (2015)
Chapter 12. Multimedia
The current version of iOS brings some changes to multimedia playback and functionality, especially the AVFoundation framework. In this chapter, we will have a look at those additions and some of the changes.
NOTE
Make sure that you have imported the AVFoundation framework in your app before running the code in this chapter.
12.1 Reading Out Text with the Default Siri Alex Voice
Problem
You want to use the default Alex Siri voice on a device to speak out some text.
Solution
Instantiate AVSpeechSynthesisVoice with the identifier initializer and pass the value of AVSpeechSynthesisVoiceIdentifierAlex to it.
Discussion
Let’s create an example out of this. Create your UI so that it looks like this. Place a text view on the screen and a bar button item in your navigation bar. When the button is pressed, you will ask Siri to speak out the text inside the text view.
Figure 12-1. Text view and button in the UI
I’ve linked the text view to a property in my view controller called textView:
@IBOutlet var textView: UITextView!
When the Read button is pressed, check first whether Alex is available:
guard let voice = AVSpeechSynthesisVoice(identifier:
AVSpeechSynthesisVoiceIdentifierAlex) else{
print("Alex is not available")
return
}
Instances of AVSpeechSynthesisVoice have properties such as identifier, quality, and name. The identifier can be used later to reconstruct another speech object. If all you know is the identifier, then you can recreate the speech object using that. The quality property is of typeAVSpeechSynthesisVoiceQuality and can be equal to values such as Default or Enhanced. Let’s print these values to the console:
print("id = \(voice.identifier)")
print("quality = \(voice.quality)")
print("name = \(voice.name)")
Then create the voice object (of type AVSpeechUtterance) with your text view’s text:
let toSay = AVSpeechUtterance(string: textView.text)
toSay.voice = voice
Last but not least, instantiate the voice synthesizer of type AVSpeechSynthesizer and ask it to speak out the voice object:
let alex = AVSpeechSynthesizer()
alex.delegate = self
alex.speakUtterance(toSay)
See Also