在iPhone上切割视频

时间:2013-06-11 15:48:40

标签: ios video

我有来自设备相机的视频文件 - 例如存储为/private/var/mobile/Media/DCIM/100APPLE/IMG_0203.MOV,我需要剪切此视频的前10秒。我可以使用哪些API或库?

1 个答案:

答案 0 :(得分:1)

我找到了标准API的解决方案:AVAssetExportSession

- (void)getTrimmedVideoForFile:(NSString *)filePath withInfo:(NSArray *)info
{
//[[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:filePath] options:nil];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality];

// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSAllDomainsMask, YES);
// NSString *outputURL = paths[0];
NSFileManager *manager = [NSFileManager defaultManager];
// [manager createDirectoryAtPath:outputURL withIntermediateDirectories:YES attributes:nil error:nil];
// outputURL = [outputURL stringByAppendingPathComponent:@"output.mp4"];
NSString *outputURL = [NSString stringWithFormat:@"/tmp/%@.mp4", [info objectAtIndex:2]];
NSLog(@"OUTPUT: %@", outputURL);
// Remove Existing File
// [manager removeItemAtPath:outputURL error:nil];

if (![manager fileExistsAtPath:outputURL]) {
    exportSession.outputURL = [NSURL fileURLWithPath:outputURL];
    exportSession.shouldOptimizeForNetworkUse = YES;
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;
    CMTime start = kCMTimeZero;
    CMTime duration = kCMTimeIndefinite;
    if ([[NSString stringWithFormat:@"%@", [info objectAtIndex:3]] floatValue] > 20.0) {
        start = CMTimeMakeWithSeconds(1.0, 600);
        duration = CMTimeMakeWithSeconds(10.0, 600);
    }

    CMTimeRange range = CMTimeRangeMake(start, duration);
    exportSession.timeRange = range;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
        switch (exportSession.status) {
            case AVAssetExportSessionStatusCompleted:
                NSLog(@"Export Complete %d %@", exportSession.status, exportSession.error);
                [self sendVideoPreview:info];
                break;
            case AVAssetExportSessionStatusFailed:
                NSLog(@"Failed:%@",exportSession.error);
                // [self addToDelayed:info withAction:@"add"];
                break;
            case AVAssetExportSessionStatusCancelled:
                NSLog(@"Canceled:%@",exportSession.error);
                // [self addToDelayed:info withAction:@"add"];
                break;
            default:
                break;
        }
    }];
} else {
    [self sendVideoPreview:info];
}