ios - AVSpeechSynthesizer错误: An AVSpeechUtterance shall not be enqueued twice

标签 ios swift avspeechsynthesizer

我有点卡住了。

这是我的代码:

let speaker = AVSpeechSynthesizer()
var playQueue = [AVSpeechUtterance]() // current queue
var backedQueue = [AVSpeechUtterance]() // queue backup

...

func moveBackward(_ currentUtterance:AVSpeechUtterance) {
    speaker.stopSpeaking(at: .immediate)
    let currentIndex = getCurrentIndexOfText(currentUtterance)
    // out of range check was deleted
    let previousElement = backedQueue[currentIndex-1]
    playQueue.insert(previousElement, at: 0)
    for utterance in playQueue {
        speaker.speak(utterance) // error here
    }
}

根据文档AVSpeechSynthesizer.stopSpeaking(at:):

Stopping the synthesizer cancels any further speech; in constrast with when the synthesizer is paused, speech cannot be resumed where it left off. Any utterances yet to be spoken are removed from the synthesizer’s queue.

当我在 AVSpeechSynthesizer 队列中插入 AVSpeechUtterance 时,我总是收到错误(AVSpeechUtterance 不得排队两次)。但根据医生的说法,它应该停止。

最佳答案

当玩家停止时,话语肯定会从队列中删除。

但是,在您的 moveBackward 中函数,您插入另一个 AVSpeechUterranceplayQueue[0]其完整数组代表玩家队列。

假设停止发生在currentIndex = 2 ,以下快照证明同一个对象在队列中注入(inject)了两次:

  • 复制backedQueue[1]这是 playQueue[1] 的副本(相同的内存地址)enter image description here

  • 插入backedQueue[1]playQueue[0] (原 playQueue[1] 变为新 playQueue[2])enter image description here

不幸的是,正如系统所指示的,AVSpeechUtterance 不应排队两次,而这正是您在这里所做的:playQueue 索引 0 和 2 处的对象具有相同的内存地址.

在索引 0 处插入新对象后的最后一个循环要求语音合成器将所有话语放入其全新队列中...其中两个是相同的。

而不是复制 playedQueue进入backedQueue (它们的对象都包含相同的内存地址)或者在两个数组中附加相同的话语,我建议创建不同的话语实例,如下所示:

    for i in 1...5 {

        let stringNb = "number " + String(i) + " of the speech synthesizer."
        let utterance = AVSpeechUtterance(string: stringNb)
        playQueue.append(utterance)

        let utteranceBis = AVSpeechUtterance(string: stringNb)
        backedQueue.append(utteranceBis)
    }

按照这条建议,您不应遇到错误 AVSpeechUtterance 不得排队两次

关于ios - AVSpeechSynthesizer错误: An AVSpeechUtterance shall not be enqueued twice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53606746/

相关文章:

ios - 禁用 AVSpeechSyntesizer/AVSpeechUtterance 的自动日期检测

ios - 实时速率和音调调整 Swift

iOS:AVSpeechSynthesizer 在使用 SFSpeechRecognizer 录制后不起作用

ios - iOS 13 Core Data 持久化存储迁移过程中出现错误

ios - 删除 Controller (B) 中的表行时,如何更新 Controller (A) 中的标签?

ios - Swift:如何通过委托(delegate)使用属性观察者

ios - 在不选择通用应用程序的情况下检测iPhone还是iPad

swift - 在创建用户之前检查 Firebase 错误以及文本字段是否为空

swift - '无效更新 : invalid number of rows in section 1

swift - 捕获立体声音频数据