我已经实现了以下代码,通过使用将我的所有文本转换为语音AVSpeechSynthesizer
。以此代码为例,您可以通过您的代码进行尝试。
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)
}
}
}
}
此代码在我的模拟器和设备中都有效。我希望这对你也有用。您应该尝试使用您的数据进行委托。