因为实验室的原因,经常接触语音这一块,之前一直用的VoiceOver将文本转化为语音,但是VoiceOver开放的API较少,所以这次用了AVSpeechSynthesis。
AVSpeechSynthesizer调用speakUtterance方法来将文本转化为语音,而speakUtterance方法需要一个参数,这个参数是AVSpeechUtterance实例的,它将包含所要读的文本,并且可以设置朗读的速度,强度和音量等。
1. 最主要的几行代码如下:
AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc]init]
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:text];
[synthesizer speakUtterance:utterance];
2. 这样就可以将text转化为语音了,设置速度,强度和音量用如下参数:
utterance.rate = 0.5; //最小为0.0,最大为1.0
utterance.pitchMultiplier = 1; //0.5-2.0之间
utterance.volume = 0.75; //0.0-1.0之间
3. 暂停和继续阅读
[synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate]; //这里可以设置是立即停止阅读还是读完这个词再暂停
[synthesizer continueSpeaking];
4. 逐句阅读:将切分好的句子一个一个放到AVSpeechUtterance中进行朗读,就像队列一样
// 按句切分
textSplitArr = [text componentsSeparatedByString:@"。"];
totalUtterances = [textSplitArr count];
currentUtterance = 0;
totalTextLength = 0;
spokenTextLengths = 0;
for (i = 0;i < [textSplitArr count];i++) {
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:textSplitArr[i]];
utterance.rate = 0.5;
utterance.pitchMultiplier = 1;
utterance.volume = 0.75;
[synthesizer speakUtterance:utterance];
}
5. 高亮文本:这个要用到AVSpeechSynthesizer代理里的方法,主要是获取正在阅读的那句utterance的range,从而将那句话进行不同颜色和字体的属性添加。
(void)speechSynthesizer:(AVSpeechSynthesizer )synthesizer willSpeakRangeOfSpeechString: (NSRange)characterRange utterance:(AVSpeechUtterance )utterance { NSString testStr = utterance.speechString; //这里是将整篇文本都设为黑色
NSMutableAttributedString textAttribute = [[NSMutableAttributedString alloc] initWithString:text]; [textAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, text.length-1)]; [textAttribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15.0] range:NSMakeRange(0,text.length-1)]; //找到正在读的那句话的range并且设置,这里range是通过didFinishSpeechUtterance这个方法来找的 [textAttribute addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(spokenTextLengths, testStr.length+1)]; [textAttribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15.0] range:NSMakeRange(spokenTextLengths,testStr.length+1)];list text here
self.textView.attributedText = textAttribute;
}//其实就是找到正在读的那句话在整篇文本中的起始位置,也就是已经读完的文本的长度要记录下来,这里用来记录。+1是因为要把每一句的句号也算进长度里。
(void)speechSynthesizer:(AVSpeechSynthesizer )synthesizer didFinishSpeechUtterance:(AVSpeechUtterance )utterance { spokenTextLengths = spokenTextLengths + [utterance.speechString length] +1; }
6. 总结
AVSpeechSynthesizer的用法其实很简单,还可以合成不同的声音,个人觉得还是很好用的。 这是iOS小白的第一篇博文,内容比较浅显,若有不对之处还希望大家多多指教,望共同进步!