iOS多个本地音频合并

项目中需求收款后进行语音播报,IOS12之后使用了推送扩展方式,通过修改本地推送通知的sound来进行语音播报功能;但是IOS15更新后,发现原来循环发送本地推送的方式有问题,语音播出来停顿严重,所以需要寻求另外的方案来解决,所以想到对音频进行合并,下面就是实例的代码:

/**
 *  音频合并
 *
 *  @param soundArr 资源文件数组
*   @params completionBlock 执行完成的回调
 */
- (void)mergeAudioWithSoundArray:(NSArray *)soundArr completionBlock:(CompletionBlock)completionBlock
{
    NSMutableArray  *audioAssetArr = [NSMutableArray arrayWithCapacity:0];
    // 音频轨道数组
    NSMutableArray  *audioCompositionTrackArr = [NSMutableArray arrayWithCapacity:0];
    // 音频素材轨道数组
    NSMutableArray  *audioAssetTrackArr = [NSMutableArray arrayWithCapacity:0];

    AVMutableComposition *audioCompostion = [AVMutableComposition composition];

    for (NSString *soundStr in soundArr)
    {
        NSString *audioPath = [[NSBundle mainBundle] pathForResource:soundStr ofType:@"mp3"];
        AVURLAsset *audioAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:audioPath]];
        [audioAssetArr addObject:audioAsset];
        // 音频轨道
        AVMutableCompositionTrack *audioCompositionTrack = [audioCompostion addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
        [audioCompositionTrackArr addObject:audioCompositionTrack];
        // 音频素材轨道
        AVAssetTrack *audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];
        [audioAssetTrackArr addObject:audioAssetTrack];

    }
    float audioDuration = 0.0f;
    //设置拼接的时间,第一个音频时为kCMTimeZero,第二个音频时为第一个音频的duration,第三个音频时为第一个音频.duration+第二个音频.duration,第四个音频时为第一个音频.duration+第二个音频.duration+第三个音频.duration,后面的依次类推
    CMTime cmTime = kCMTimeZero;
    for (int i = 0; i < audioAssetArr.count; i ++)
    {
        if (i == 0) {
            cmTime = kCMTimeZero;
        } else {
            cmTime = CMTimeAdd(cmTime, audioAssetArr[i-1].duration);
        }
        // 音频合并 - 插入音轨文件
        [audioCompositionTrackArr[i] insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAssetArr[i].duration) ofTrack:audioAssetTrackArr[i] atTime:cmTime error:nil];
        // 将每个音频的时间加起来
        audioDuration += CMTimeGetSeconds(audioAssetArr[i].duration);
        
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    fileManager.delegate = self;
    
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:audioCompostion presetName:AVAssetExportPresetAppleM4A];
    NSString *outPutFilePath = [[self.filePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"paySound.m4a"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:outPutFilePath])
    {
        [[NSFileManager defaultManager] removeItemAtPath:outPutFilePath error:nil];
    }
    session.outputURL = [NSURL fileURLWithPath:outPutFilePath];
    session.outputFileType = @"com.apple.m4a-audio"; 
    session.shouldOptimizeForNetworkUse = YES; 
    
    [session exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{

            switch ([session status]) {
                case AVAssetExportSessionStatusFailed: {
                    NSString *error = [[session error] description];
                    NSLog(@"合成失败:%@", error);
                    completionBlock(NO, audioDuration);
                } break;

                case AVAssetExportSessionStatusCancelled: {
                    completionBlock(NO, audioDuration);
                } break;

                case AVAssetExportSessionStatusCompleted: {
                    //获取分组的共享目录
                    NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.xxxx.appgroup"];//此处id要与开发者中心创建时一致
                    // 要先创建Sounds目录,不然复制文件的时候会报Sounds不是一个目录
                    NSURL *filePathURL = [groupURL URLByAppendingPathComponent:@"Library/Sounds"];
                    NSError *error = nil;
                    [fileManager createDirectoryAtURL:filePathURL withIntermediateDirectories:YES attributes:nil error:&error];
                    NSURL *fileURL = [groupURL URLByAppendingPathComponent:@"Library/Sounds/sound.m4a"];
                    // 每次都先删除原来的文件
                    if ([[NSFileManager defaultManager] fileExistsAtPath:fileURL.path]) {
                        NSError *err = nil;
                        [[NSFileManager defaultManager] removeItemAtURL:fileURL error:&err];
                    }
                    // 复制文件到appgroup中
                    NSError *err = nil;
                    BOOL copyRes = [[NSFileManager defaultManager] copyItemAtPath:outPutFilePath toPath:fileURL.path error:&err];
                    completionBlock(copyRes, audioDuration);

                } break;

                default: {
                    completionBlock(NO, audioDuration);
                } break;
            }

        });
    }];
}

音频合成导出的路径

- (NSString *)filePath
{
    if (!_filePath)
    {
        _filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
        _filePath = [_filePath stringByAppendingPathComponent:@"user"];
        NSFileManager *manage = [NSFileManager defaultManager];
        if ([manage createDirectoryAtPath:_filePath withIntermediateDirectories:YES attributes:nil error:nil])
        {
            _filePath = [_filePath stringByAppendingPathComponent:@"testAudio.aac"];
        }
        tempName = mp3Name;
    }

合成语音后,发本地推送,修改声音

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.sound = [UNNotificationSound soundNamed:[NSString stringWithFormat:@"sound.m4a"]];
content.userInfo = @{@"locationPlaySound":@"1"};
if (@available(iOS 15, *)) {
    // IOS15必须设置title或者body才能播放自定义的语音
    content.body = [NSString localizedUserNotificationStringForKey:@"支付收款到账" arguments:nil];
}
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
NSString *identifier = [NSString stringWithFormat:@"%@-%f",@"noticeId",audioDuration];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
[center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
// 等语音播报完后再通知系统本地通知完成了,避免收到其他推送信息中断语音播报
     dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, audioDuration * NSEC_PER_SEC);
     dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            completed();
     });
}];

你可能感兴趣的:(iOS多个本地音频合并)