AVSpeechUtterance in Swift

AVSpeechUtterances is a very useful feature in iOS that allows you to perform text-to-speech with just a few lines of code. This is especially useful when you are dealing with dynamic user content.

Implementing a AVSpeechUtterance is simple, start by importing AVFoundation() so that you can use the AVSpeechUtterance protocol.

import AVFoundation

In your class, define a variable for the AVSpeechSynthesizer.

var speechsynth = AVSpeechSynthesizer()

Now, you can initiate the actual speech. Initiating the AVSpeechUtterance is simple, just specify the utterance, the language, and the rate, then you can start the utterance. You can specify any string you want, including dynamic content.

let utter = AVSpeechUtterance(string: "Enter a String you want here.")
        utter.voice = AVSpeechSynthesisVoice(language: "en-US") //Supports multiple languages
        utter.rate = 0.5 //Set the rate of speech
        speechsynth.delegate = self //Set the delegate of the AVSpeechSynthesizer
        speechsynth.speak(utter) //Speak!

Of course, you may need to stop the utterance in the middle. Simply use either of the below:

narrator.stopSpeaking(at: .immediate)
//OR
narrator.stopSpeaking(at: .word)

Thank you for reading this post. Feel free to leave a reply if you have any questions or comments. I will be posting a video on how to make a Text to Speech app soon on my YouTube Channel (https://www.youtube.com/channel/UC7SHcFdjkcz55dRXBhiIxog).

Leave a Reply

Your email address will not be published. Required fields are marked *