Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## AVSpeechSynthesizer
- * アラートで入力した文字を音声で再生する
- ```swift
- 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)
- }
- }
- ```
Add Comment
Please, Sign In to add comment