IOS text-to-speech (TTS) Explanation: Swift, iostts
The previous blog explains the speech recognition function of the iOS speech FrameWork: speech.
TTS is simple. It does not have permission settings or a lot of Code. The Code is as follows:
Import UIKitimport AVFoundationimport MediaPlayerclass ViewController: UIViewController, AVSpeechSynthesizerDelegate {let synth = AVSpeechSynthesizer () // TTS object let audioSession = AVAudioSession. sharedInstance () // voice engine override func viewDidLoad () {super. viewDidLoad () synth. delegate = self} // press the button to start the speech func speechMessage (message: String) {if! Message. isEmpty {do {// set up the speech environment to ensure that the voice can be read (especially when the speech recognition is just done, this sentence must be added, otherwise there is no sound) try audioSession. setCategory (AVAudioSessionCategoryAmbient)} catch let error as NSError {print (error. code)} // The text to be converted to let utterance = AVSpeechUtterance. init (string: message) // sets the language, which is utterance. voice = AVSpeechSynthesisVoice. init (language: "zh_CN") // sets the utterance sound size. volume = 1 // set the audio utterance. pitchMultiplier = 1.1 // start to read synth. s Peak (utterance) }}// press the button to end the speech func StopSpeech () {// interrupt the speech synth immediately. stopSpeaking (at: AVSpeechBoundary. immediate) // synth. stopSpeaking (at: AVSpeechBoundary. word) can also end the speech, but when the previous speech is interrupted, it is impossible to read another text immediately.} // What to do after the speech ends (proxy method) func speechSynthesizer (_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {// code }}
You can also write the code into a class: SpeechUtil. You don't need to change the code. You can call the speechMessage and StopSpeech methods of the class. If you want to use the proxy method, don't forget SpeechUtil (). synth. delegate = self