Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Created July 17, 2018 21:52
Show Gist options
  • Save KentarouKanno/f5e6884e77f413a6da2191365f4ab2b5 to your computer and use it in GitHub Desktop.
Save KentarouKanno/f5e6884e77f413a6da2191365f4ab2b5 to your computer and use it in GitHub Desktop.

AVSpeechSynthesizer

  • アラートで入力した文字を音声で再生する
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)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment