Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text to speech conversion in Swift 4

I'm trying to integrate text to speech functionality in my iOS app.

For this I'm using AVSpeechUtterance and AVSpeechSynthesisVoice classes of AVFoundation framework.

extension String {
    func speech(with pronunciation: String) {
        let utterance = AVSpeechUtterance(attributedString: NSAttributedString(string: self, attributes: [.accessibilitySpeechIPANotation : pronunciation]))
        utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
        let synth = AVSpeechSynthesizer()
        DispatchQueue.main.async {
            synth.speak(utterance)
        }
    }
}

The problem I'm facing is with the pronunciation of wind word as verb and noun, i.e.

  1. wind as a verb is pronounced: waɪnd
  2. and wind as a noun is pronounced: wɪnd

The above pronunciation strings follow the International Phonetic Alphabet (IPA).

But, I'm not getting the expected results.

like image 544
PGDev Avatar asked Dec 08 '25 19:12

PGDev


1 Answers

If you want an IPA translation of a specific spelling, I suggest to use the iOS feature located at:

  • Settings > General > Accessibility > Speech > Pronunciations (iOS 12).
  • Settings > Accessibility > Spoken Content > Pronunciations (iOS 13)

Once you choose the desired result, you can use it in your code to be vocalized by the speech synthesizer.

EDIT

this solution also doesn't work for me.

I'm quite surprised by your comment because when I follow every steps of the provided link, I get the code snippet hereunder:

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let pronunciationKey = NSAttributedString.Key(rawValue: AVSpeechSynthesisIPANotationAttribute)

//        let attrStr = NSMutableAttributedString(string: "blablablaNOUN",
//                                                attributes: [pronunciationKey: "ˈwɪnd"])
    let attrStr = NSMutableAttributedString(string: "blablablaVERB",
                                            attributes: [pronunciationKey: "ˈwa͡ɪnd"])
        let utterance = AVSpeechUtterance(attributedString: attrStr)

        let synthesizer = AVSpeechSynthesizer()
        synthesizer.speak(utterance)
}

... and when I launch this blank app after changing the iPhone Language in the Settings - General - Language & Region menu, I get the correct pronunciations for the verb and the noun.

Copy-paste the code snippet hereabove and test it by yourself.

like image 127
XLE_22 Avatar answered Dec 11 '25 09:12

XLE_22



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!