Text to speech conversion in Swift 4

依然范特西╮ 提交于 2019-12-24 06:49:41

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/55009246/text-to-speech-conversion-in-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!