文字読み上げ機能概要
ボタンを押すと指定した文字を読み上げてくれるシンプルな機能。
version
swift4.2
参考動画
以下のYoutube動画を参考にしました。
https://www.youtube.com/watch?time_continue=1081&v=MO_09UCI5i0
コード
SpeechService.swiftというファイルを用意して、このファイル内で読み上げ機能の設定をします。
languageの箇所を変更すると他の言語で読み上げてくれます。
使える言語はiPhoneにインストールされているもので、日本語、英語、中国語など様々です。
SpeechService.swift
import UIKit
import AVFoundation
class SpeechService {
private let synthesizer = AVSpeechSynthesizer()
// 再生速度を設定
var rate: Float = AVSpeechUtteranceDefaultSpeechRate
// 言語を英語に設定
var voice = AVSpeechSynthesisVoice(language: "en-US")
func say(_ phrase: String) {
// 話す内容をセット
let utterance = AVSpeechUtterance(string: phrase)
utterance.rate = rate
utterance.voice = voice
synthesizer.speak(utterance)
}
func getVoices() {
AVSpeechSynthesisVoice.speechVoices().forEach({ print($0.language) })
}
}
ViewControllerでspeechServiceクラスのsay関数を呼び出す事で引数の文字列を読み上げてくれます。
speechService.say("hoge")とするとhogeと読み上げてくれます。
ViewController.swift
import UIKit
import AVFoundation
class ViewController: UIViewController{
let speechService = SpeechService()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func touchedButton(_ sender: Any) {
speechService.say("hoge")
}
}
今回は、ViewControllerのtouchedButtonとストーリーボードが紐づいているので、ボタンを押す事で、文字が読み上げられます。
