上一篇博客講解了iOS的speech FrameWork語音識別的功能:http://www.cnblogs.com/qian-gu-ling/p/6599670.html,對應的這篇博客就寫一下文本轉語音。
TTS很簡單,沒有權限設置,也沒有一大堆代碼,代碼如下:
import UIKit import AVFoundation import MediaPlayer class ViewController: UIViewController,AVSpeechSynthesizerDelegate { let synth = AVSpeechSynthesizer() //TTS對象 let audioSession = AVAudioSession.sharedInstance() //語音引擎 override func viewDidLoad() { super.viewDidLoad() synth.delegate = self } // 按按鈕開始語音 func speechMessage(message:String){ if !message.isEmpty { do { // 設置語音環境,保證能朗讀出聲音(特別是剛做過語音識別,這句話必加,不然沒聲音) try audioSession.setCategory(AVAudioSessionCategoryAmbient) }catch let error as NSError{ print(error.code) } //需要轉的文本 let utterance = AVSpeechUtterance.init(string: message) //設置語言,這里是中文 utterance.voice = AVSpeechSynthesisVoice.init(language: "zh_CN") //設置聲音大小 utterance.volume = 1 //設置音頻 utterance.pitchMultiplier = 1.1 //開始朗讀 synth.speak(utterance) } } //按按鈕結束語音 func StopSpeech() { // 立即中斷語音 synth.stopSpeaking(at: AVSpeechBoundary.immediate) // synth.stopSpeaking(at: AVSpeechBoundary.word)也能結束語音,但遇到中斷上一個語音,立即朗讀另一個文本就做不到。 } // 語音結束之后要做的事(代理方法) func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { // code } }
寫的知識點比較完整,大家也可以把這些代碼寫成一個類:SpeechUtil,基本不用改什么,調用類的speechMessage和StopSpeech方法就行了,若要走代理方法,別忘了SpeechUtil().synth.delegate = self