我想要做的是按下说话按钮,它将突出显示第一段然后说出该段落,然后将下一段滚动到 textView 的中心并突出显示该段落并说出它等等。我必须添加什么代码才能做到这一点?
import UIKit
import AVFoundation
class TestViewController: UIViewController, AVSpeechSynthesizerDelegate {
let synthesizer = AVSpeechSynthesizer()
@IBOutlet weak var textViewOutlet: UITextView!
@IBAction func pauseSpeech(_ sender: Any) {
synthesizer.pauseSpeaking(at: AVSpeechBoundary.word)
}
@IBAction func stopSpeech(_ sender: Any) {
synthesizer.stopSpeaking(at: .word)
}
@IBAction func cancelButton(_ sender: Any) {
synthesizer.continueSpeaking()
}
@IBAction func speak(_ sender: AnyObject) {
let string = textViewOutlet.text!
let utterance = AVSpeechUtterance(string: string)
utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
synthesizer.speak(utterance)
}
override func viewDidLoad() {
super.viewDidLoad()
synthesizer.delegate = self
textViewOutlet.font = .systemFont(ofSize: 20)
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
let mutableAttributedString = NSMutableAttributedString(string: utterance.speechString)
mutableAttributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: NSMakeRange(0, (utterance.speechString as NSString).length))
mutableAttributedString.addAttribute(.foregroundColor, value: UIColor.red, range: characterRange)
textViewOutlet.attributedText = mutableAttributedString
textViewOutlet.font = .systemFont(ofSize: 20)
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
textViewOutlet.attributedText = NSAttributedString(string: utterance.speechString)
textViewOutlet.font = .systemFont(ofSize: 20)
}
}