当我们使用AVSpeechSynthesizer来播放语音时,有时会遇到错误提示“AVSpeechSynthesizer Error: AVSpeechUtterance should not be enqueued twice.” 这个错误通常是因为我们尝试将同一个AVSpeechUtterance对象排队两次导致的。为了解决这个问题,我们可以采取以下方法:
if synthesizer.isSpeaking {
synthesizer.stopSpeaking(at: .immediate)
}
let speechUtterance = AVSpeechUtterance(string: "Hello, World!")
speechUtterance.voice = AVSpeechSynthesisVoice(language: "en-US")
synthesizer.speak(speechUtterance)
确保不会多次排队同一个utterance对象,以避免出现错误。