I have implemented following code to make my all text to voice conversion by using AVSpeechSynthesizer
. This code as a example, you can try by your code.
class TextToVoiceVC: UIViewController, AVSpeechSynthesizerDelegate {
var arrSpeechCount = ["One", "Two", "Three", "Four", "Five", "Six", "Seven"]
var count : Int = 0
let speechSynthesizer = AVSpeechSynthesizer()
//----------------------------------------------------------------
// MARK:- AVSpeechSynthesixerDelegate
//----------------------------------------------------------------
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
}
//----------------------------------------------------------------
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
speechSynthesizer.stopSpeaking(at: .word)
count += 1
if count < arrSpeechCount.count {
let speechUtterance = AVSpeechUtterance(string: (arrSpeechCount[count]))
DispatchQueue.main.async {
self.speechSynthesizer.speak(speechUtterance)
}
}
}
//----------------------------------------------------------------
// MARK:- View Life Cycle Methods
//----------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
speechSynthesizer.delegate = self
}
//----------------------------------------------------------------
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Code to start speech
if speechSynthesizer.isSpeaking {
speechSynthesizer.stopSpeaking(at: .immediate)
} else {
let speechUtterance = AVSpeechUtterance(string: (arrSpeechCount[count]))
DispatchQueue.main.async {
self.speechSynthesizer.speak(speechUtterance)
}
}
}
}
This code is working in my both simulator as well as device. I hope this will useful to you also. You should try delegate with your data.