iOS极光推送后台播放语音(类似支付宝到账提示)

最近做了一个项目就是说接收到推送消息之后不管是在前台还是在后台都需要播放一条自定义的语音类似于支付宝到账提示的那种,这里就不多说了

这里主要是对 iOS 10 以上的设备

首先要想程序进入后台 或者程序杀死之后接受到数据 然后播放语音

(1) APP 进入后台然后播放语音这种情况可以走静默推送(可以百度静默推送)这里就不说这个了
(2)这里主要是讲程序杀死了之后 接收到推送然后播放对应的语音

1 第一步 想要在后台播放语音需要设置 Capabilities 里面的 Background Modes 如图
屏幕快照 2018-05-04 上午9.24.57.png

需要用到 推送扩展 NotificationService (极光必传mutable-content = 1) 使用原生 API AVSpeechSynthesizer实现文字合成语音

屏幕快照 2018-05-04 上午9.29.54.png

新建一个这个类


屏幕快照 2018-05-04 上午9.31.05.png

之后会发现
屏幕快照 2018-05-04 上午9.31.29.png

之后会在程序中看到这个


屏幕快照 2018-05-04 上午9.33.04.png
#import "NotificationService.h"
#import <AVFoundation/AVFoundation.h>
@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@property (nonatomic, strong) AVSpeechSynthesizer *synthesizer;
@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    // Modify the notification content here...
//    self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title];
    //  解析推送自定义参数userInfo
    NSString *content = [self.bestAttemptContent.userInfo objectForKey:@"contents"];
    [self syntheticVoice:content];
    self.contentHandler(self.bestAttemptContent);
}

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    self.contentHandler(self.bestAttemptContent);
}
- (void)syntheticVoice:(NSString *)string {
    
    //  语音合成
    self.synthesizer = [[AVSpeechSynthesizer alloc] init];

    //创建一个会话
    AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:string];
    
    //选择语言发音的类别,如果有中文,一定要选择中文,要不然无法播放语音
    utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    
    //播放语言的速率,值越大,播放速率越快
    utterance.rate = 0.5f;
    
    //音调  --  为语句指定pitchMultiplier ,可以在播放特定语句时改变声音的音调、pitchMultiplier的允许值一般介于0.5(低音调)和2.0(高音调)之间
    utterance.pitchMultiplier = 1.0f;
    
    //让语音合成器在播放下一句之前有短暂时间的暂停,也可以类似的设置preUtteranceDelay
    utterance.postUtteranceDelay = 0.1f;
    
    //播放语言
    [self.synthesizer speakUtterance:utterance];
    
}


@end

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容