可以使用AVSpeechSynthesizerDelegate中的方法来检测发音是否结束。在发音结束时,将启动AVSpeechSynthesizer。代码示例如下:
class ViewController: UIViewController, AVSpeechSynthesizerDelegate { let synthesizer = AVSpeechSynthesizer() var speaking = false
override func viewDidLoad() { super.viewDidLoad() //设置delegate synthesizer.delegate = self }
@IBAction func speak(_ sender: UIButton) { let utterance = AVSpeechUtterance(string: "Hello, world!") synthesizer.speak(utterance) speaking = true }
@IBAction func stop(_ sender: UIButton) { synthesizer.stopSpeaking(at: .immediate) }
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { speaking = false //检测发音是否结束 if !synthesizer.isSpeaking { synthesizer.speak(utterance) speaking = true } } }