Apple has provided a powerful api to play audio from text and here are the steps to achieve:
1- Import AVFoundation framework
2- Initialise AVSpeechSynthesizer(as below)
let synthesizer = AVSpeechSynthesizer()
3- Create an instance of AVSpeechUtterance, using this you can set various parameters like voice, language, pitch, delay and rate to text to be spoken.
let utterance = AVSpeechUtterance(string: text to be spoken)
4- Assign speak utterance to synthesise initialzed above.
synthesizer.speakUtterance(utterance)
5- One can use synthesizer object to stop and pause speech using methods provided:
func stopSpeakingAtBoundary(boundary: AVSpeechBoundary) -> Bool
func pauseSpeakingAtBoundary(boundary: AVSpeechBoundary) -> Bool
above AVSpeechBoundary is speech constraint which describse when speech is to be paused or stopped.
Sample Code (In Swift)
let synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: text to be spoken)
utterance.rate = 0.5
utterance.voice = AVSpeechSynthesisVoice(language: "fr-FR")
synthesizer.speakUtterance(utterance)
0 Comment(s)