首页 > 解决方案 > Swift - AVSpeechSynthesizer - 如何运行回调 onError

问题描述

AVSpeechSynthesizer习惯用德语发音一些文本。有时它工作得很好,有时它不是出于我不知道的原因(没有错误,因为该speak()方法没有抛出,我唯一能观察到的是控制台中记录的以下消息):

_BeginSpeaking: couldn't begin playback

我试图在AVSpeechSynthesizerDelegate发生错误时在其中找到一些 API 来注册回调,但我没有找到。

最接近的匹配是这个(但它似乎只适用于 macOS,而不适用于 iOS):https ://developer.apple.com/documentation/appkit/nsspeechsynthesizerdelegate/1448407-speechsynthesizer?changes=_10

您可以在下面找到我如何在我的应用程序中初始化和使用语音合成器:

class Speaker: NSObject, AVSpeechSynthesizerDelegate {
  class func sharedInstance() -> Speaker {
    struct Singleton {
      static var sharedInstance = Speaker()
    }
    return Singleton.sharedInstance
  }
   
  let audioSession = AVAudioSession.sharedInstance()
  let synth = AVSpeechSynthesizer()
   
  override init() {
    super.init()
    synth.delegate = self
  }
   
  func initializeAudioSession() {
    do {
      try audioSession.setCategory(.playback, mode: .spokenAudio, options: .duckOthers)
      try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
    } catch {
       
    }
  }
   
  func speak(text: String, language: String = "de-DE") {
    guard !self.synth.isSpeaking else { return }

    let utterance = AVSpeechUtterance(string: text)
    let voice = AVSpeechSynthesisVoice.speechVoices().filter { $0.language == language }.first!
     
    utterance.voice = voice
    self.synth.speak(utterance)
  }
}

音频会话初始化在应用程序启动期间运行一次。

之后,通过运行以下代码来合成语音:

Speaker.sharedInstance.speak(text: "Lederhosen")

问题是我无法知道语音合成是否成功——UI 显示“正在说话”状态,但实际上没有说话。

标签: iosswifttext-to-speechavaudiosession

解决方案


推荐阅读