A paragraph of text, let the system with the voice broadcast, using avfoundation frame Avspeechsynthesizer can, very simple.
Step 1, import the Avfoundation framework:
1 Import avfoundation
Step 2, create the speech synthesizer:
1 /// Speech synthesizer 2 private lazy var speechsynthesizer:avspeechsynthesizer = {3let speech = Avspeechsynthesizer ()4 return speech5 } ()
Step 3, Play voice:
1 ///Voice Broadcast Method2 ///3 ///-Parameter text: Textual content4 Privatefunc Playvoicewithtext (text:string) {5 6 //no sound is played before stopping (prevent: voice too long, last not finished)7 //Immediate: Immediately8 //Word: Play the last time, and then play this9 speechsynthesizer.stopspeaking (at:. Immediate)Ten One //Instantiate language-read English by default ALet speechutterance = Avspeechutterance (string: Text) - - //Specify the playback language theLet voice = Avspeechsynthesisvoice (language:"ZH-CN") -Speechutterance.voice =Voice - - //Broadcast + speechsynthesizer.speak (speechutterance) -}
Voice Broadcast-Text to system sound