其实人就是最牛的TTS
文本转语音技术, 也叫TTS, 是Text To Speech的缩写. iOS如果想做有声书等功能的时候, 会用到这门技术.
iOS7之后才有该功能
需要 AVFoundation 库
AVSpeechSynthesizer: 语音合成器, 可以假想成一个可以说话的人, 是最主要的接口
AVSpeechSynthesisVoice: 可以假想成人的声音
AVSpeechUtterance: 可以假想成要说的一段话
0x000 代码示例, 朗读唐诗静夜思

class TTSExample:AVSpeechSynthesizerDelegate { 

 let av=AVSpeechSynthesizer() 

 init(){ 

 av.delegate=self 

 } 

 func 朗读静夜思() { 

 let jingyesi=“静夜思,李白,床前明月光,疑是地上霜,举头望明月,低头思故乡” //标点符号会产生朗读时的停顿, 这样就有节奏了 

 let utterance=AVSpeechUtterance(string: jingyesi) 

 utterance.rate=AVSpeechUtteranceDefaultSpeechRate 

 let voiceType=AVSpeechSynthesisVoice(language: "zh-CN") 

 utterance.voice=voiceType 

 av.speakUtterance(utterance) 

 } 

 fun 停止朗读(){ 

 av.stopSpeakingAtBoundary(.Immediate) 

 } 

 func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didFinishSpeechUtterance utterance: AVSpeechUtterance) { 

 print(“已经朗读完了”) 

 //如果想循环播放,可以在这里调用如下代码: 

 // av.speakUtterance(utterance) 

 } 

 }


如果想在后台播放, 需要在配置里设置:
配置后台播放
同时在AppDelegate里启用:

let session=AVAudioSession.sharedInstance() 

 try! session.setCategory(AVAudioSessionCategoryPlayback) 

 try! session.setActive(true) 

 0x01 AVSpeechSynthesizer


这个类就像一个会说话的人, 可以”说话”, 可以”暂停”说话, 可以”继续”说话, 可以判断他当前是否正在说话.有以下的方法或者属性:
说话: speakUtterance
控制: continueSpeaking(继续说), pauseSpeakingAtBoundary(暂停说话), paused(暂停状态的属性), speaking(说话的状态), stopSpeakingAtBoundary(停止说话)
委托: delegate
0x02 AVSpeechBoundary
这是一个枚举. 在暂停, 或者停止说话的时候, 停下的方式用这个枚举标示. 包括两种:
AVSpeechBoundaryImmediate: 立即停
AVSpeechBoundaryWord : 说完一个整词再停
0x03 AVSpeechSynthesizerDelegate
合成器的委托, 对于一些事件, 提供了响应的接口.
didCancelSpeechUtterance: 已经取消说话
didContinueSpeechUtterance: 已经继续说话
didFinishSpeechUtterance: 已经说完
didPauseSpeechUtterance: 已经暂停
didStartSpeechUtterance:已经开始
willSpeakRangeOfSpeechString:将要说某段话
0x04 AVSpeechSynthesisVoice
AVSpeechSynthesisVoice定义了一系列的声音, 主要是不同的语言和地区.
voiceWithLanguage: 根据制定的语言, 获得一个声音.
speechVoices: 获得当前设备支持的声音
currentLanguageCode: 获得当前声音的语言字符串, 比如”ZH-cn”
language: 获得当前的语言
0x05 AVSpeechUtterance
这个类就是一段要说的话. 主要的属性和方法有:
pitchMultiplier: 音高
postUtteranceDelay: 读完一段后的停顿时间
preUtteranceDelay: 读一段话之前的停顿
rate: 读地速度, 系统提供了三个速度: AVSpeechUtteranceMinimumSpeechRate, AVSpeechUtteranceMaximumSpeechRate, AVSpeechUtteranceDefaultSpeechRate
speechString: 要读的字符串
voice: 使用的声音, 是AVSpeechSynthesisVoice对象
volume: 音量
0x06 UML关系图