ios - 在 Swift 中使用 WillSpeakRange 委托(delegate)中断 AVSpeechUtterance 和恢复

标签 ios swift avspeechsynthesizer

使用 AVSpeechSynthesizer,如果一段话很长,我想提示用户是将其切断还是听到结束。

我在 willSpeakRange 委托(delegate)中跟踪长度。

在某个时刻,我想暂停或停止演讲。然后询问用户是否继续。

如果我在原始话语上使用合成器的暂停功能,它似乎不允许我用“你想听完吗”来打断。

另一方面,如果我使用停止功能,它允许我问“你想听到最后吗”,但我们失去了原始话语中的位置。

如何暂停或停止原始话语,然后恢复或捕获剩余文本以开始有效地完成原始话语的新话语。

这是我使用的代码:

let count = 0
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
count = count+1
if (count==limit) {
count = 0
//Pause option does not seem to allow interjection
self.voice.pauseSpeaking(at: AVSpeechBoundary.immediate)
//stop option loses place
self.voice.stopSpeaking(at: .immediate)
//NEED TO CAPTURE UNSPOKEN TEXT IF I USE STOP OPTION
let speechString = utterance.speechString
let newRange = Range(characterRange, in: speechString)
//Store the remaining text to a variable       
remainingText = ???
self.speakSomething(text:",,Should I stop or continue?")
}

最佳答案

If I use the Pause functionality of the synthesizer on the original utterance, it does not seem to allow me to interrupt with "Do you want to hear to the end".

pauseSpeaking 方法不会影响语音合成要说出的队列。只要您愿意,它就会暂停,并允许从您离开的地方继续,但此时您不能按照这种模式即时插入任何新的话语

On the other hand, if I use the Stop functionality, it allows me to ask "Do you want to hear to the end" but we lose the place in the original utterance.

stopSpeaking 方法从合成器的队列中删除任何尚未说出的话语,这就是为什么您可以插入新话语但会丢失之前安排的所有内容的原因。 p>

How can I pause or stop the original utterance and then either resume or capture the remaining text to start a new utterance that effectively completes the original one.

根据我上面的解释,你别无选择,只能停止原来的话语来问你的问题。我建议这种模式:

  1. 借助 AVSpeechSynthesizerDelegate 协议(protocol)获取当前语音。
  2. 触发 stopSpeaking 合成器方法,该方法将从队列中删除尚未说出的话语。
  3. 创建话语以提出选择问题并让合成器读出。
  4. 如果选择继续,请从 1. 中找到的位置创建一个新话语,直到文本结束,然后继续。

如果你不知道如何捕捉潜台词,看看这个example (ObjC, Swift) 以粗体文本显示口语单词。

在此示例的委托(delegate)方法中添加以下代码片段以捕获您剩余的文本:

func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer,
                       willSpeakRangeOfSpeechString characterRange: NSRange,
                       utterance: AVSpeechUtterance) {

    let remainingText = utterance.speechString.dropFirst(characterRange.location)
    //...
}

按照这些步骤,您可以在 Swift 中使用 WillSpeakRange Delegate 中断 AVSpeechUtterance 并恢复,如帖子标题中所述。

关于ios - 在 Swift 中使用 WillSpeakRange 委托(delegate)中断 AVSpeechUtterance 和恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56460923/

相关文章:

ios - 使用 iTunes 恢复备份安装相同应用程序的两个 iOS 设备的identifierForVendor 可以相同吗?

php - 如何在 Xcode 5 中使用 UITextField 内容更新 MySQL 数据库?

ios - 不支持解析 GeoQuery 'withinKilometres'

javascript - WKWebView是否可以关闭位置权限?

ios - 实时更改 AVSpeechUtterance 速率

ios - 使用 Text-To-Speech postUtteranceDelay 时回避背景音乐不会取消回避

iphone - 请解释这个 Objective-C 代码

ios - 如何禁用滑动手势识别器?

快速倒数计时器 - 显示剩余的天数小时秒数

ios - 我们可以为 AVSpeechSynthesizer 提供自定义语音吗