DEV Community

Swee Sen
Swee Sen

Posted on • Edited on

3

Swift: Text to Speech in any Language

To start with text to speech, the code below is the basic setup.

let utterance = AVSpeechUtterance(string: "Some text")
utterance.voice = AVSpeechSynthesisVoice(language: "en") //any language that you prefer
let synth = AVSpeechSynthesizer()
synth.speak(utterance)

Enter fullscreen mode Exit fullscreen mode

However, this code requires us to specify the language of the text in the code. To make it more dynamic by allowing it to speak any text by automatically detecting the language, we can use NSLinguisticTagger.dominantLanguage(for: text) to detect the language of the text.


if let language = NSLinguisticTagger.dominantLanguage(for: text) {

    //we now know the language of the text 

    let utterance = AVSpeechUtterance(string: text)
    utterance.voice = AVSpeechSynthesisVoice(language: language) //use the detected language

    let synth = AVSpeechSynthesizer()
    synth.speak(utterance)
} else {
    print("Unknown language")
}

Enter fullscreen mode Exit fullscreen mode

Additionally, we can also control the speed of the speech as well as the pitch/frequency of the speech:

private func readText(_ text:String){
    if let language = NSLinguisticTagger.dominantLanguage(for: text) {
        let utterance = AVSpeechUtterance(string: text)
        utterance.voice = AVSpeechSynthesisVoice(language: language)

        //control speed and pitch
        utterance.pitchMultiplier = 1
        utterance.rate = 0.2

        let synth = AVSpeechSynthesizer()
        synth.speak(utterance)

    } else {
        print("Unknown language")
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more