ios 推送语音播报

分享一个类似支付宝收款提醒的语音播报,我这里推送配的是个推,集成配置都可以参照个推文档中心,文档介绍步骤都很详细。

1、打开推送Capabilities---Push Notifications


2、开启远程推送Capabilities---Background Modes---Remote Notifications


3、新建UNNotification Service Extension

File---New---Target,选UNNotification Service Extension


新建完成后你会发现多了几个文件


4、开始编码

添加声音依赖库AVFoundation,NotificationService.m中代码如下,现在可以去个推官方推一条试试了。后台推的是透传消息,在项目在前台运行时,可以自行添加声音方法。

#import "NotificationService.h"
#import <AVFoundation/AVSpeechSynthesis.h>
#import <MediaPlayer/MediaPlayer.h>

@interface NotificationService ()<AVSpeechSynthesizerDelegate>

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

@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];
   
    self.contentHandler(self.bestAttemptContent);
    
    [self startSpeaking:self.bestAttemptContent.body];
    
}

- (void)startSpeaking:(NSString *)words{
    
    // 创建语音合成器
    AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init];
    synthesizer.delegate = self;
    // 设置语音
    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    // 转换文本
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:words];
    utterance.voice = voice;
    // 语速
    utterance.rate = 0.8;
    // 朗读的内容
    [synthesizer speakUtterance:utterance];

}

#pragma mark AVSpeechSynthesizerDelegate
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance{
    NSLog(@"开始播放");
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance*)utterance{
    NSLog(@"完成播放");
}

@end

5、其他

1)创建UNNotification Service Extension成功后,这里Bundle ID 会自动添加 .MyNotification,不需要重新配置证书

后面选择证书的地方设成默认就行

2)不太了解Notification Servivice Extension的可以先看下这篇文章,作者讲解的很详细







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值