iOS系统语音播报文字

iOS系统语音播报文字AVSpeechSynt avSpeech AVSpeechSynt alloc init AVSpeechUtte avSpeechtera AVSpeechUtte speechUttera 接下来是新闻联播

大家好,我是讯享网,很高兴认识大家。

   

    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

}

小讯
上一篇 2025-03-09 21:54
下一篇 2025-01-27 14:34

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/65024.html