ios - 在 AVSpeechSynthesis 和 AVAudioSession 之间交替

标签 ios avaudiosession avspeechsynthesizer

我有一个在说话(使用 AVSpeechSynthesizer)和聆听(使用 AVAudioSession)之间来回切换的应用程序。

如果我让说话自然地停止(它的短语结束),然后开始听,一切都会很好。但是,如果我允许用​​户打断说话,那么在(确切地说!)连续 4 次打断之后,语音合成器将停止并出现错误 Deactivating an audio session that has running I/O

这是我的AVSpeechSynthesizer 方法:

func speakMessage(theMessage: String) {
    let synth = AVSpeechSynthesizer()
    let utterance = AVSpeechUtterance(string: theMessage)
    utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
    utterance.rate = 0.52

    synth.speak(utterance)
}

func stopSpeaking() {
    let synth = AVSpeechSynthesizer()
    if synth.isSpeaking {
        synth.stopSpeaking(at: .immediate)
        let utterance = AVSpeechUtterance(string: "")
        synth.speak(utterance)
        synth.stopSpeaking(at: .immediate)
    }
}

这里是AVAudioSession方法,一直到报错的地方:

private func startRecording() throws {

    // Cancel the previous task if it's running.
    if let recognitionTask = recognitionTask {
        recognitionTask.cancel()
        self.recognitionTask = nil
    }

    let audioSession = AVAudioSession.sharedInstance()
    try audioSession.setCategory(AVAudioSessionCategoryRecord)
    try audioSession.setActive(true, with: .notifyOthersOnDeactivation)

    recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
    ...

我假设调用 try audioSession.setActive(true .. 是错误发生的地方 - AVAudioSession 首先尝试停用,但文档说

Deactivating your session will fail if any associated audio objects (such as queues, converters, players, or recorders) are currently running

当用户中断语音合成时,我如何安全地停用 Audio Session ?

最佳答案

我今天遇到了这个问题,经过一些试验后,我发现在停止合成器之前暂停它可以停用 Audio Session 而不会出错。所以,这就是我的 stopSpeaking() 方法的样子:

var synthesizer = AVSpeechSynthesizer()

....

func stopSpeaking() {
    synthesizer.pauseSpeaking(at: .immediate)
    synthesizer.stopSpeaking(at: .immediate)
}

顺便说一句,只有在 .immediate 边界调用 stopSpeaking(at:) 时才会发生错误。如果该方法将 .word 作为参数,至少在我的情况下,停用 Audio Session 不会导致错误。

关于ios - 在 AVSpeechSynthesis 和 AVAudioSession 之间交替,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48722346/

相关文章:

ios - AVAudioSession setActive :NO not resuming ipod playback

iphone - 从Dropbox加载文件

iOS - 在 UIWebView 中加载 PDF,然后使用 UIDocumentInteractionController 保存到 iBooks

ios - 枚举内存使用

ios - 是否可以在后台模式下播放avaudioplayer?

iOS 文字转语音 : What decides the default voice returned by [AVSpeechSynthesisVoice voiceWithLanguage]?

ios - OpenCV 线/标尺检测

ios - 应用程序重新激活后 AVAudioSession 无法播放声音

ios - AVSpeechUtterance 和 Swift 中没有语音/语音缺失

ios - AVSpeechUtterance 静音模式下的发音