import UIKit
import AVFoundation
import PlaygroundSupport
var str = "Turning to Right"
let synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: str)
utterance.rate = 0.39 // more the rate more faster words will be uttered
utterance.voice = AVSpeechSynthesisVoice(language: "en-US") // fr-FR en-US // hub of all codes:- https://gist.github.com/vitoziv/9108407
//for playground only
let playerViewController = AVPlayerViewController()
PlaygroundPage.current.liveView = playerViewController.view
//
synthesizer.speak(utterance)
// instructions to enable sound in background mode
1. tick the Audio, Airplay, and Picture in Picture functionality in background mode
2. add the following line in viewWillAppear function
override func viewWillAppear(_ animated: Bool) {
try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
}
3. enclose your code of synthesizer.speak() to other in
DispatchQueue.global().sync {
}
to run in global main thread.
ENJOY!!