在iOS7之前,想要实现语音播报文字内容,可能需要第三方资源库来实现。现在在iOS7上,系统为我们提供了语音播报文字的功能,我们不仅可以播报英语内容,也可以播报汉语文字,所以对于开发者来说真是个福音如下代码所示,
if( [[[UIDevice currentDevice] systemVersion] integerValue] >= 7.0)
{
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:warnmsg];
utterance.rate *= 0.8;
AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
//获取当前系统语音
NSString *preferredLang = @"";
if (m_strLang == "zh-Hans")
{
preferredLang = @"zh-CN";
}else{
preferredLang = @"en-US";
}
AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:[NSString stringWithFormat:@"%@",preferredLang]];
utterance.voice = voice;
[synth speakUtterance:utterance];
[synth release];
}
首先,判断设备的系统在iOS7或更高版本,接下来就是关键的AVSpeechUtterance和AVSpeechSynthesizer,从代价可以看出AVSpeechUtterance是设置需要播报的文字内容-warnmsg、语音速率-rate以及语言种类-preferredLang,而AVSpeechSynthesizer就是开始同步播放的类。
上面的代码节选自我项目中的部分代码,有一些变量也没有实际的意义,直接拷贝肯定不行,所以想要实现该功能,还是自己写一些变量内容,例如warnmsg = @"今天天气真好,工作加油";来测试一下。
上面的代码只能在前台运行,如果退到后台的话则不能运行,如果想要在推送的时候播报文字语音,那么这就有点蛋疼了。好在也有解决方法,在AppDelegate的applicationDidLaunch的代码中加上如下代码,则可支持后台语音播报文字内容,
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
}
本人建了一个ios交流群188647173,有兴趣的可以加群进来相互交流。