由于项目需要,运动轨迹功能需要加入321倒计时语音播报功能。经过网上了解,苹果自带AVFoundationFramework包括语音播报功能,实现起来也很简单。
实现过程如下:
1. #import <AVFoundation/AVFoundation.h>
2.alloc语音合成对象
3.创建并配置utterance
本人是将语音播报封装成一个独立的单例model来实现播报功能的调用
- (id)init {
self = [super init];
if (!self) {
return nil;
}
_speechSynth = [[AVSpeechSynthesizer alloc]init];
return self;
}
+ (SpeechModel*)sharedInstance{
static dispatch_once_t oncePredicate;
static SpeechModel *_sharedInstance = nil;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[SpeechModel alloc] init];
});
return _sharedInstance;
}
- (void)speech:(NSString*)str english:(BOOL)b{
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:str];
utterance.pitchMultiplier = 1.0; //高低音控制
utterance.rate = AVSpeechUtteranceDefaultSpeechRate;
if (b) {
//英式发音
AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
utterance.voice = voice;
}else{
//中式发音
AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"]; //@"zh-CN"
utterance.voice = voice;
}
// NSLog(@"%@",[AVSpeechSynthesisVoice speechVoices]);
[_speechSynth speakUtterance:utterance];
}
如果未定义utterance.voice属性,语音将自动跟随系统
到此,语音播报实现功能全部完成,方法能自动将文字转化为语音读出,不足之处就是进入后台,播报会自动停止。或者在后台运动语音播报时,会收到播报中断通知,使语音无法正常播报。接下来,我们就是要做相关配置,使能支持后台播报。
项目中是使用后台定位回调,来实现后台语音播报方法的调用。当然,你也可以使用远程推送的方式来实现后台播报的调用。使用远程推送时,注意playload的配置,"content-available"
= 1;
//必带字段
,相关文章可通过下面链接学习远程推送知识。
http://www.cocoachina.com/ios/20160908/17511.html
接下来对工程进行配置,使支持后台语音
//使语音支持后台播报
NSError *error = NULL;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
if(error) {
// Do some error handling
}
[session setActive:YES error:&error];
if (error) {
// Do some error handling
}
工程中增加上述代码,本人将代码加在单例类中