iOS多個本地音頻合并

項目中需求收款后進行語音播報,IOS12之后使用了推送擴展方式,通過修改本地推送通知的sound來進行語音播報功能;但是IOS15更新后,發現原來循環發送本地推送的方式有問題,語音播出來停頓嚴重,所以需要尋求另外的方案來解決,所以想到對音頻進行合并,下面就是實例的代碼:

/**
 *  音頻合并
 *
 *  @param soundArr 資源文件數組
*   @params completionBlock 執行完成的回調
 */
- (void)mergeAudioWithSoundArray:(NSArray *)soundArr completionBlock:(CompletionBlock)completionBlock
{
    NSMutableArray <AVURLAsset *> *audioAssetArr = [NSMutableArray arrayWithCapacity:0];
    // 音頻軌道數組
    NSMutableArray <AVMutableCompositionTrack *> *audioCompositionTrackArr = [NSMutableArray arrayWithCapacity:0];
    // 音頻素材軌道數組
    NSMutableArray <AVAssetTrack *> *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();
     });
}];
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容