Swift Text To Speech Synthesizer

Mazen Kilani
Geek Culture
Published in
3 min readMay 30, 2021
AppsGym Books App Ms. Chips Reading the Book Synopsis

Swift’s Text to Speech Synthesizer Can Speak Aloud the Contents of Text Fields and Views.

Scenario

Our app will utilise a text to speech synthesizer (also, synthesiser), which we shall affectionately call Ms. Chips, in the Book Details view. Ms Chips will read aloud the text of the Synopsis field.

Technique

We shall utilise Swift’s AVSpeechSynthesizerDelegate functions, where the BookDetailsViewController, which contains the Synopsis field and Ms. Chips robot button, acts as the delegate.

Audience

The article is for Swift developers who seek complete, proven, code-centric solutions to speed up their development projects. The code snippets below can be used with minimal customisation (your app designated UITextView).

App Model

We based the article on the AppsGym Books model app, published on Apple’s App Store (as 8Books), and you can download the complete Xcode project on AppsGym.com, for free.

User Interfaces

Ms. Chips, AppsGym Books Robot Synthesizer Default Icon
Ms. Chips, AppsGym Books Robot Synthesizer While Speaking Icon

The UI is an icon button of Ms. Chips, with a toggle switch. Tap once to start speaking and tap again to stop.

Logic

BookDetailsViewController.swift controls the start/stop of Ms. Chips synthesizer. The BookDetailsViewController acts as a delegate to AVSpeechSynthesizer, hence implements the required delegate functions.

Our charming robot, Ms. Chips, will be represented by a button on the Book Details view, which acts as a toggle on/off switch. Tap once to start, tap again to stop. Hence, we need the following functions: didStart utterance: AVSpeechUtterance and didFinish utterance: AVSpeechUtterance. We shall also change the button icon image to indicate the status (slient or speaking).

In addition, Ms. Chips should stop reading aloud if the user dismisses the view. Hence, we need the viewDidDisappear() to stop the synthesizer robot speaking.

Code

BookDetailsViewController.swift viewDidLoad()

BookDetailsViewController.swift robotButtonAction()

BookDetailsViewController.swift Synthesizer Delegate Functions

Too Easy for You?

We can make our synthesizer more interesting by utilising Swift’s methods to control Rate, Pitch and Volume. Then we change Voice, with different dialects and languages. You can research and update your app now, but we shall publish a dedicated article at a later date. Stay tuned!

The article covered the complete setup and code to implement a ‘quick and easy’ text to speech synthesizer, in the Book Details view. The synthesizer will read aloud the text of the book Synopsis UITextView. Hope you find it useful in your app. Thanks for reading!

--

--

Mazen Kilani
Geek Culture

I published 47 Swift iOS apps/games and 2 Flutter Android apps. I share complete Xcode projects, free (no ads), at AppsGym.com.