To start with text to speech, the code below is the basic setup.
letutterance=AVSpeechUtterance(string:"Some text")utterance.voice=AVSpeechSynthesisVoice(language:"en")//any language that you preferletsynth=AVSpeechSynthesizer()synth.speak(utterance)
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 useNSLinguisticTagger.dominantLanguage(for: text)
to detect the language of the text.
ifletlanguage=NSLinguisticTagger.dominantLanguage(for:text){//we now know the language of the textletutterance=AVSpeechUtterance(string:text)utterance.voice=AVSpeechSynthesisVoice(language:language)//use the detected languageletsynth=AVSpeechSynthesizer()synth.speak(utterance)}else{print("Unknown language")}
Additionally, we can also control the speed of the speech as well as the pitch/frequency of the speech:
privatefuncreadText(_text:String){ifletlanguage=NSLinguisticTagger.dominantLanguage(for:text){letutterance=AVSpeechUtterance(string:text)utterance.voice=AVSpeechSynthesisVoice(language:language)//control speed and pitchutterance.pitchMultiplier=1utterance.rate=0.2letsynth=AVSpeechSynthesizer()synth.speak(utterance)}else{print("Unknown language")}}
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse