我试图在Swift中使用AVFoundation Text to Speech功能来说出一个基于参数更改的自定义String。如何在单词之间实现暂停?
让我们说这是我的字符串:
var spokenSentence = "I like Toast with lots of Butter, but banana is nice"
如何在“黄油”后3秒暂停TTS?
这是我关于TTS的代码:
var spokenSentence = "I like Toast with lots of Butter, but banana is nice"
let synth = AVSpeechSynthesizer()
var utterance = AVSpeechUtterance(string: spokenSentence)
然后
synth.speak(utterance)
除了MacOS上的swift之外我听说你可以使用[[slnc 1000]]在Swift中有类似的功能吗?
似乎AVSpeechUtterance
有preUtteranceDelay
或postUtteranceDelay
等房地产。您可以通过编写一些预处理代码来利用这些功能:
extension AVSpeechSynthesizer {
func speekWithDelay(_ text: String) {
let pattern = #"([^{]*)(?:\{([0-9]+(?:\.[0-9]+))\})?"#
let regex = try! NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: text, options: .anchored, range: NSRange(0..<text.utf16.count))
for match in matches {
let utteranceText = text[Range(match.range(at: 1), in: text)!]
let utterance = AVSpeechUtterance(string: String(utteranceText))
if let range = Range(match.range(at: 2), in: text) {
let delay = TimeInterval(text[range])!
utterance.postUtteranceDelay = delay
}
speak(utterance)
}
}
}
用它作为:
let synth = AVSpeechSynthesizer()
@IBAction func speakButtonPressed(_ sender: Any) {
let spokenSentence = "I like Toast with lots of Butter,{3} but banana is nice"
synth.speekWithDelay(spokenSentence)
}
请记住,AVSpeechSynthesizer
的实例需要保留在强引用中,直到最后一个话语被告知,所以你最好把它作为一个实例属性。