Text-to-Speech in Swift in 5 Lines
- Create a new Single View Application project in Xcode.
- Add the AVFoundation.Framework to the Project’s Linked Framworks and Libraries.
- Import AVFoundation in the ViewController.swift file.
- In the ViewController.swift file in the viewDidLoad function, add the following code:
// Line 1. Create an instance of AVSpeechSynthesizer.
var speechSynthesizer = AVSpeechSynthesizer()
// Line 2. Create an instance of AVSpeechUtterance and pass in a String to be spoken.
var speechUtterance: AVSpeechUtterance = AVSpeechUtterance(string: “This is a test. This is only a test. If this was an actual emergency, then this wouldn’t have been a test.”)
//Line 3. Specify the speech utterance rate. 1 = speaking extremely the higher the values the slower speech patterns. The default rate, AVSpeechUtteranceDefaultSpeechRate is 0.5
speechUtterance.rate = AVSpeechUtteranceMaximumSpeechRate / 4.0
// Line 4. Specify the voice. It is explicitly set to English here, but it will use the device default if not specified.
speechUtterance.voice = AVSpeechSynthesisVoice(language: “en-US”)
// Line 5. Pass in the urrerance to the synthesizer to actually speak.
6. Run the application and you will hear Siri speak your custom text.