import UIKit import AVFoundation extension Date { func toString(format: String) -> String { let dateFormat = DateFormatter() dateFormat.dateFormat = format return dateFormat.string(from: self) } } class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! let synth = AVSpeechSynthesizer() var timer = Timer() @IBAction func startHandler(_ sender: UIButton) { timer.invalidate() timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] (timer) in guard let weakSelf = self else { return } let text = "現在時刻:" + Date().toString(format: "HH:mm") weakSelf.textView.text = text let myUtterance = AVSpeechUtterance(string: text) myUtterance.voice = AVSpeechSynthesisVoice(language: "zh-TW") myUtterance.rate = 0.5 weakSelf.synth.speak(myUtterance) } timer.fire() } @IBAction func endHandler(_ sender: UIButton) { timer.invalidate() synth.stopSpeaking(at: .word) } }
這是一個可以一直報時的簡易程式
參考資料:
https://code.tutsplus.com/tutorials/create-a-text-to-speech-app-with-swift--cms-22229
全站熱搜
留言列表