トップ 最新 追記

Cocoa練習帳

iOS/iPhone/iPad/watchOS/tvOS/MacOSX/Android プログラミング, Objective-C, Cocoa, Swiftなど

2012|01|02|03|04|05|06|07|08|09|10|11|12|
2013|01|02|03|04|05|06|07|08|09|10|11|12|
2014|01|02|03|04|05|06|07|08|09|10|11|12|
2015|01|02|03|04|05|06|07|08|09|10|11|12|
2016|01|02|03|04|05|06|07|08|09|10|11|12|
2017|01|02|03|04|05|06|07|08|09|10|11|12|
2018|01|02|03|04|05|06|07|08|09|10|11|12|
2019|01|02|03|04|05|06|07|08|09|10|11|12|
2020|01|02|03|04|05|06|07|08|09|10|11|12|
2021|01|02|03|04|05|06|07|08|09|10|11|12|
2022|01|02|03|04|05|06|07|08|09|10|11|12|
2023|01|02|03|04|05|06|07|08|09|10|11|12|
2024|01|02|03|

2023-10-10 [macOS][iOS] TextToSpeech

文章を読み上げる機能は、過去、様々な年化があったが、これが現在の方法のようだ。

文章と音声の設定する。

// Create an utterance.
let utterance = AVSpeechUtterance(string: text)
 
// Configure the utterance.
utterance.rate = 0.57
utterance.pitchMultiplier = 0.8
utterance.postUtteranceDelay = 0.2
utterance.volume = 0.8
 
// Retrieve the Japanese voice.
let voice = AVSpeechSynthesisVoice(language: "ja-JP")
 
// Assign the voice to the utterance.
utterance.voice = voice

文章を読み上げる。

// Create a speech synthesizer.
synthesizer = AVSpeechSynthesizer()
 
// Tell the synthesizer to speak the utterance.
synthesizer!.speak(utterance)

これをSwiftUIで利用できるようにする。

struct ContentView: View {
    @State var text = ""
    @State var synthesizer: AVSpeechSynthesizer?
    var body: some View {
        VStack {
            TextField("Input text", text: $text)
            Button(action: {
                // Create an utterance.
                let utterance = AVSpeechUtterance(string: text)
                 
                // Configure the utterance.
                utterance.rate = 0.57
                utterance.pitchMultiplier = 0.8
                utterance.postUtteranceDelay = 0.2
                utterance.volume = 0.8
                 
                // Retrieve the Japanese voice.
                let voice = AVSpeechSynthesisVoice(language: "ja-JP")
                 
                // Assign the voice to the utterance.
                utterance.voice = voice
                 
                // Create a speech synthesizer.
                synthesizer = AVSpeechSynthesizer()
                 
                // Tell the synthesizer to speak the utterance.
                synthesizer!.speak(utterance)
            }) {
                Text("Say")
            }
        }
        .padding()
    }
}
 
#Preview {
    ContentView()
}

文章やAVSpeechSynthesizerのインスタンスは@Stateで永続的に保持し、バインディングでTextFieldの値を渡している。

_ 【ソースコード】

GitHubからどうぞ。
https://github.com/murakami/workbook/tree/master/multiplatform/TextToSpeech - GitHub

トップ 最新 追記