3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift4.2で文字読み上げ機能実装

Last updated at Posted at 2019-08-04

文字読み上げ機能概要

ボタンを押すと指定した文字を読み上げてくれるシンプルな機能。

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とストーリーボードが紐づいているので、ボタンを押す事で、文字が読み上げられます。

スクリーンショット 2019-07-06 15.27.41.png
3
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?