Guest User

Untitled

a guest
Jul 17th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. ## AVSpeechSynthesizer
  2.  
  3. * アラートで入力した文字を音声で再生する
  4.  
  5. ```swift
  6. import UIKit
  7. import AVFoundation
  8.  
  9. class ViewController: UIViewController {
  10.  
  11. var speechText: String = ""
  12.  
  13. override func viewDidLoad() {
  14. super.viewDidLoad()
  15.  
  16. }
  17.  
  18. @IBAction func showAlert(_ sender: UIButton) {
  19.  
  20. let alert = UIAlertController(title: "今日の予定は?", message: "", preferredStyle: .alert)
  21. let speechAction = UIAlertAction(title: "Speech", style: .default, handler: { (_) -> Void in
  22. // TextFieldから値を取得
  23. if let text = alert.textFields?.first?.text {
  24. self.speechText = text
  25. self.voice()
  26. }
  27. })
  28.  
  29. let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
  30.  
  31. alert.addAction(speechAction)
  32. alert.addAction(cancel)
  33. alert.addTextField { (textField) in }
  34. present(alert, animated: true, completion: nil)
  35. }
  36.  
  37. func voice() {
  38. let talker = AVSpeechSynthesizer()
  39. let utterance = AVSpeechUtterance(string: "今日の予定は\(speechText)です。")
  40. utterance.voice = AVSpeechSynthesisVoice(language: "ja-JP")
  41. talker.speak(utterance)
  42. }
  43. }
  44.  
  45. ```
Add Comment
Please, Sign In to add comment