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

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more