【发布时间】:2017-09-08 14:14:20
【问题描述】:
试图在 AVSpeechSynthesizer 操作期间突出显示一个单词。朗读文本,但单词未突出显示。该文本包含在 func speechSynthesizer() 中的文本视图 infoTxt 中。
仍然需要弄清楚如何在说话后取消突出显示。
@IBAction func ReadText(_ sender: UIButton) {
if !self.synth.isSpeaking {
let textParagraphs = self.infoTxt.text.components(separatedBy: "\n")
self.totalUtterance = textParagraphs.count
for pieceOfText in textParagraphs {
let speechUtterance = AVSpeechUtterance(string: pieceOfText)
let voice = AVSpeechSynthesisVoice(language: "en GB")
speechUtterance.voice = voice
_ = AVSpeechSynthesisVoice.speechVoices()
self.synth.speak(speechUtterance)
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
let mutableAttributedString = NSMutableAttributedString(string: utterance.speechString)
mutableAttributedString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellow, range: characterRange)
infoTxt.attributedText = mutableAttributedString
}
}else {
self.synth.continueSpeaking()
}
myUtterance = AVSpeechUtterance(string: infoTxt.text)
myUtterance.rate = 0.1
_ = AVSpeechSynthesisVoice()
synth.speak(myUtterance)
_ = AVSpeechSynthesisVoice(language: "Tom")
}
@IBAction func PauseText(_ sender: Any) {
self.synth.pauseSpeaking(at: AVSpeechBoundary.word)
}
@IBAction func StopText(_ sender: Any) {
self.synth.stopSpeaking(at: AVSpeechBoundary.immediate)
}
【问题讨论】:
-
你设置委托了吗?
-
Yesclass ViewController: UIViewController, AVSpeechSynthesizerDelegate
-
不,我的意思是
my.synth.delegate = self -
嗨,笑话人,我是这么认为的: let synth = AVSpeechSynthesizer() var myUtterance = AVSpeechUtterance(string: "")
标签: ios swift text highlighting