最近做了一個項目就是說接收到推送消息之后不管是在前臺還是在后臺都需要播放一條自定義的語音類似于支付寶到賬提示的那種,這里就不多說了
這里主要是對 iOS 10 以上的設(shè)備
首先要想程序進(jìn)入后臺 或者程序殺死之后接受到數(shù)據(jù) 然后播放語音
(1) APP 進(jìn)入后臺然后播放語音這種情況可以走靜默推送(可以百度靜默推送)這里就不說這個了
(2)這里主要是講程序殺死了之后 接收到推送然后播放對應(yīng)的語音
1 第一步 想要在后臺播放語音需要設(shè)置 Capabilities 里面的 Background Modes 如圖
需要用到 推送擴(kuò)展 NotificationService (極光必傳mutable-content = 1) 使用原生 API AVSpeechSynthesizer實現(xiàn)文字合成語音
新建一個這個類
之后會發(fā)現(xiàn)
之后會在程序中看到這個
#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];
// 解析推送自定義參數(shù)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];
//創(chuàng)建一個會話
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:string];
//選擇語言發(fā)音的類別昵观,如果有中文稽物,一定要選擇中文樱哼,要不然無法播放語音
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
//播放語言的速率,值越大梯醒,播放速率越快
utterance.rate = 0.5f;
//音調(diào) -- 為語句指定pitchMultiplier 端盆,可以在播放特定語句時改變聲音的音調(diào)切黔、pitchMultiplier的允許值一般介于0.5(低音調(diào))和2.0(高音調(diào))之間
utterance.pitchMultiplier = 1.0f;
//讓語音合成器在播放下一句之前有短暫時間的暫停暮的,也可以類似的設(shè)置preUtteranceDelay
utterance.postUtteranceDelay = 0.1f;
//播放語言
[self.synthesizer speakUtterance:utterance];
}
@end