注册
iOS

iOS 自定义通知声音

iOS 自定义通知声音

场景

在消息推送里面播放自定义生成的声音

解决方案

  1. 生成自定义声音文件后,必须要写入到【/Library/Sounds/】才能进行播放
///往声音目录/Library/Sounds/写入音频文件
- (void)writeMusicDataWithUrl:(NSString*)filePath
callback:(void(^)(BOOL success,NSString * fileName))blockCallback{
NSString *bundlePath = filePath;
NSString *libPath = [NSHomeDirectory() stringByAppendingString:@"/Library/Sounds/"];

NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:libPath]) {
NSError *error;
[manager createDirectoryAtPath:libPath withIntermediateDirectories:YES attributes:nil error:&error];
}

NSData *data = [NSData dataWithContentsOfFile:bundlePath];

BOOL flag = [data writeToFile:[libPath stringByAppendingString:[filePath lastPathComponent]] atomically:YES];
if (flag) {
NSLog(@"文件写成功");
if (blockCallback) {
blockCallback(YES,[filePath lastPathComponent]);
}
}else{
NSLog(@"文件写失败");
if (blockCallback) {
blockCallback(NO,nil);
}
}
}

  1. 在【UNMutableNotificationContent】的【sound】参数中写入文件名
///!!!!:推送语音播报
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; //标题
content.sound = [UNNotificationSound soundNamed:fileName];

content.body = @"语音播报";// 本地推送一定要有内容,即body不能为空。

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 150000
if (@available(iOS 15.0, *)) {
content.interruptionLevel = UNNotificationInterruptionLevelTimeSensitive;//会使手机亮屏且会播放声音;可能会在免打扰模式(焦点模式)下展示
// @"{\"aps\":{\"interruption-level\":\"time-sensitive\"}}";
// @"{\"aps\":{\"interruption-level\":\"active\"}}";
content.body = @"语音播报";// 本地推送一定要有内容,即body不能为空。
}
#endif
// repeats,是否重复,如果重复的话时间必须大于60s,要不会报错
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01 repeats:NO];
/* */
//添加通知的标识符,可以用于移除,更新等搡作
NSString * identifier = [[NSUUID UUID] UUIDString];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
[center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
completed();
}];

参考: http://www.jianshu.com/p/a6eba8cfb… blog.csdn.net/LANGZI77585…

https://juejin.cn/post/7029245981149364255

0 个评论

要回复文章请先登录注册