Speech Synthesizer on iOS

2 minutes, 38 seconds

iOS has a library called ‘AVSpeechSynthesizer’ since iOS7 that allows app to ‘speak out’ the text from any kind of string, or even attributed string to voice.

1. Create a Single View App

Create a new single view app with Xcode. Go to Main.storyboard, create the scene to be like this.

AA

By using a assistant mode, create an IBOutlet from UITextView for textView and create an IBAction to a new action called speak(_ sender: Any).

2. Prepare View Controller

At ViewController.swift, import this framework at the header part.


import AVFoundation

Now we have to edit our IBAction function.


@IBAction func speak(_ sender: Any) {
  let myText = textView.text
  let speechUtterance = AVSpeechUtterance(string: myText!)
  
  // rate is using Float but we just use this parameter from system
  // to get consistent speech rate
  speechUtterance.rate = AVSpeechUtteranceDefaultSpeechRate
  
  // you may change the language from the language list
  speechUtterance.voice =  AVSpeechSynthesisVoice(language:"en-US")
  
  let speechSynth = AVSpeechSynthesizer.init()
  speechSynth.delegate = self
  speechSynth.speak(speechUtterance)
  
}

On this code we use identifier “en-US” which refer to English for US on this code AVSpeechSynthesisVoice(language:"en-US").

However you may change for another languages that are supported like on this list.


ar-SA
cs-CZ
da-DK
de-DE
el-GR
en-AU
en-GB
en-IE
en-US
en-ZA
es-ES
es-MX
fi-FI
fr-CA
fr-FR
he-IL
hi-IN
hu-HU
id-ID
it-IT
ja-JP
ko-KR
nl-BE
nl-NL
no-NO
pl-PL
pt-BR
pt-PT
ro-RO
ru-RU
sk-SK
sv-SE
th-TH
tr-TR
zh-CN
zh-HK
zh-TW

So that is pretty much it, very simple to implement this feature. Type something on the Text View and press the button, the app will read your text.

3. Add Delegate

For extra control we will aslo want to callback when the the speech is finished and other things.

It’s already being declared in the IBAction function speechSynth.delegate = self, so now we have to declare and implement it.

At the class declaration add this.


AVSpeechSynthesizerDelegate

Then implement it


// MARK:- AVSpeechSynthesizerDelegate

func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
  
  print("finished speaking")
  
}

S