iOS开发技巧(语音播报文字内容)

在iOS7之前,想要实现语音播报文字内容,可能需要第三方资源库来实现。现在在iOS7上,系统为我们提供了语音播报文字的功能,我们不仅可以播报英语内容,也可以播报汉语文字,所以对于开发者来说真是个福音如下代码所示,

if( [[[UIDevice currentDevicesystemVersionintegerValue] >= 7.0)

{

    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:warnmsg];

    utterance.rate *= 0.8;

    AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer allocinit];    

    //获取当前系统语音

    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,有兴趣的可以加群进来相互交流。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值