iOS语音播报开发

    最近做APP,有用到语音播报模块,于是小记一下。语音播报即在我们使用支付宝APP,钱到账会街道一个通知类消息,并且语音播放出来,如:支付宝到账15元。或者经常听到小店里外卖系统播报:您有新的订单,请注意查收!此类语音播报,原理:在APP接收到固定的消息推送的同时,通过手机系统原生自带语音(或者调用API,如百度语音、讯飞语音等)播报出固定的消息内容。此外,还要注意在APP在后台运行时,也要注意消息的接收播报,或者应项目要求不需要播报,或者在APP被杀死的情况下也要接收推送和播报。

    下面我所说的是APP在前台运行和后台运行(不包括杀死)的情况下,接收到的消息被播报出来。

    消息推送我们集成的是极光推送,这里不再做过多阐述,语音我们暂时用的是iOS原生的,直接原生调用方法把字符串读出来。后期可能会自己录制一段语音,然后把文件加入工程中,播报使用自己的语音文件。大家也可以直接调用讯飞或百度语音,都支持的。

    首先,iOS原生语音框架是在AVFoundation里,所以我们要首先引入框架

#import <AVFoundation/AVFoundation.h>

    下面是语音播报的代码:

//语音播报
        AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:alert];
        
        utterance.pitchMultiplier=1;
        //中式发音
        AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
        
        utterance.voice = voice;
        
        NSLog(@"%@",[AVSpeechSynthesisVoice speechVoices]);
        
        AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc]init];
        
        [synth speakUtterance:utterance];

在消息推送代理方法回调中:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    NSLog(@"后台:%@",userInfo);
    if ([userInfo[@"type"]isEqual:@"1"]) {
        
        AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:userInfo[@"aps"][@"alert"]];
        
        AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
        
        [synth speakUtterance:utterance];
    }
   
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

猜你喜欢

转载自blog.csdn.net/zhonglv_honeymoon/article/details/79741704
今日推荐