タイトル : Swift-Playgrounds: 文字列を音声出力
更新日 : 2022-07-26
カテゴリ : プログラミング
タグ :
swift   

文字列を音声出力

【実演】iPadでiOSアプリを開発する!!【Swift Playgrounds】(SwiftUI) を見ていたら、AVFoundationでテキストを音声出力する例があったので試してみる。

import SwiftUI
import AVFoundation

struct ContentView: View {
    // 読み上げるメッセージ(初期値)
    @State private var msg = "こんにちわ"
    
    var body: some View {
        VStack {
            Text("テキストを読み上げるアプリ")
            TextField("test", text:$msg)
            Button(action:{
                speak(text: msg)
            }) {
                Text("押してね")
            }
        }
    }
    
    /**
     引数で渡されたテキストを音声出力する
     - parameter text: 音声出力するテキスト
     */
    func speak(text: String) {
        let synthesizer = AVSpeechSynthesizer()
        let utterance = AVSpeechUtterance(string: text)
        utterance.voice = AVSpeechSynthesisVoice(language: "ja-JP")
        synthesizer.speak(utterance)
    }
}