美文网首页
iOS自定义通知声音

iOS自定义通知声音

作者: 陈大帅 | 来源:发表于2021-11-17 10:42 被阅读0次

    场景

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

    解决方案

    生成自定义声音文件后,必须要写入到

    【/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);
            }
        }
    }
    

    在【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();
                }];
    

    阅读原文

    相关文章

      网友评论

          本文标题:iOS自定义通知声音

          本文链接:https://www.haomeiwen.com/subject/oerltrtx.html