iOS系统语音播报文字

   

    AVSpeechSynthesizer *avSpeech = [[AVSpeechSynthesizeralloc]init];

    AVSpeechUtterance *avSpeechterance = [AVSpeechUtterancespeechUtteranceWithString:@"接下来是新闻联播"];

    AVSpeechSynthesisVoice *voiceType = [AVSpeechSynthesisVoicevoiceWithLanguage:@"zh-CN"];

    avSpeechterance.voice = voiceType;

    avSpeechterance.rate *=0.4;

    [avSpeech speakUtterance:avSpeechterance];



         参考:

         

在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:[NSStringstringWithFormat:@"%@",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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值