import UIKit
import AVFoundation
class ViewController: UIViewController {
var speechText: String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showAlert(_ sender: UIButton) {
let alert = UIAlertController(title: "今日の予定は?", message: "", preferredStyle: .alert)
let speechAction = UIAlertAction(title: "Speech", style: .default, handler: { (_) -> Void in
// TextFieldから値を取得
if let text = alert.textFields?.first?.text {
self.speechText = text
self.voice()
}
})
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(speechAction)
alert.addAction(cancel)
alert.addTextField { (textField) in }
present(alert, animated: true, completion: nil)
}
func voice() {
let talker = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: "今日の予定は\(speechText)です。")
utterance.voice = AVSpeechSynthesisVoice(language: "ja-JP")
talker.speak(utterance)
}
}