iOS相册视频导出到沙盒(也可于压缩视频)

2022-10-22  本文已影响0人  非叼牛

相册视频导出到沙盒的过程踩了很多坑,现在总结一下

先上demo:

- (void)compressVideoWithVideoURL:(NSURL *)videoURL
                        saveName:(NSString *)saveName
                       completion:(void (^)(NSString *savePath))completion {

    AVURLAsset *videoAsset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSArray *presets = [AVAssetExportSession exportPresetsCompatibleWithAsset:videoAsset];
    AVAssetExportSession *session;
    
    // 选定质量
    //AVAssetExportPresetLowQuality
    //AVAssetExportPresetMediumQuality
    //AVAssetExportPresetHighestQuality   //相册原画质
    //AVAssetExportPreset640x480
    //AVAssetExportPreset960x540
    //AVAssetExportPreset1280x720
    //AVAssetExportPreset1920x1080
    NSString *exportPreset = AVAssetExportPreset1280x720;
    if ([presets containsObject:exportPreset]) {
        session = [[AVAssetExportSession alloc] initWithAsset:videoAsset presetName:exportPreset];
    }

    // 设置导出路径
    NSString *outputPath = [self getCompressVideoPathWithName:saveName];
    session.outputURL = [NSURL fileURLWithPath:outputPath];

    // Optimize for network use.
    session.shouldOptimizeForNetworkUse = true;

    NSArray *supportedTypeArray = session.supportedFileTypes;
    if ([supportedTypeArray containsObject:AVFileTypeMPEG4]) {
        // 设置导出格式
        session.outputFileType = AVFileTypeMPEG4;
    } else if (supportedTypeArray.count == 0) {
        NSLog(@"No supported file types");
        return;
    } else {
        session.outputFileType = [supportedTypeArray objectAtIndex:0];
    }

    // Begin to export video to the output path asynchronously.
    // 开始导出
    [session exportAsynchronouslyWithCompletionHandler:^{
        if ([session status] == AVAssetExportSessionStatusCompleted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion([session.outputURL path]);
                    NSLog(@"导出成功");
                }
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(nil);
                    NSLog(@"导出失败");
                }
            });
        }
    }];
}

- (NSString *)getCompressVideoPathWithName:(NSString *)name {
    NSString *documentDirectory = [(NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/CompressVideo/", documentDirectory];
    [self createPath:path];
    return [path stringByAppendingString:name];
}

- (void)createPath:(NSString *)path {
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSError *error;
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
            NSLog(@"Path Create Failed: %@", path);
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读