如何修剪video文件,并转换为20秒的video与斯威夫特?

我想修剪一个video文件。 我想从图库中selectvideo并将其转换为15秒的video。 我正在关注Objective C的这个 链接 。它对我来说很好,但我是Swift语言的初学者。 任何人都可以帮助我在Swift中转换此代码?

以下是我在Objective C中的代码:

-(void)cropVideo:(NSURL*)videoToTrimURL{ AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoToTrimURL options:nil]; AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *outputURL = paths[0]; NSFileManager *manager = [NSFileManager defaultManager]; [manager createDirectoryAtPath:outputURL withIntermediateDirectories:YES attributes:nil error:nil]; outputURL = [outputURL stringByAppendingPathComponent:@"output.mp4"]; // Remove Existing File [manager removeItemAtPath:outputURL error:nil]; // exportSession.outputURL = [NSURL fileURLWithPath:outputURL]; exportSession.shouldOptimizeForNetworkUse = YES; exportSession.outputFileType = AVFileTypeQuickTimeMovie; CMTime start = CMTimeMakeWithSeconds(1.0, 600); // you will modify time range here CMTime duration = CMTimeMakeWithSeconds(19.0, 600); CMTimeRange range = CMTimeRangeMake(start, duration); exportSession.timeRange = range; [exportSession exportAsynchronouslyWithCompletionHandler:^(void) { switch (exportSession.status) { case AVAssetExportSessionStatusCompleted: [self writeVideoToPhotoLibrary:[NSURL fileURLWithPath:outputURL]]; NSLog(@"Export Complete %d %@", exportSession.status, exportSession.error); break; case AVAssetExportSessionStatusFailed: NSLog(@"Failed:%@",exportSession.error); break; case AVAssetExportSessionStatusCancelled: NSLog(@"Canceled:%@",exportSession.error); break; default: break; } //[exportSession release]; }]; } -(void)writeVideoToPhotoLibrary:(NSURL*)aURL { NSURL *url = aURL; NSData *data = [NSData dataWithContentsOfURL:url]; // Write it to cache directory NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"file.mov"]; [data writeToFile:path atomically:YES]; // After that use this path to save it to PhotoLibrary ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:path] completionBlock:^(NSURL *assetURL, NSError *error) { if (error) { NSLog(@"%@", error.description); }else { NSLog(@"Done :)"); } }]; } 

对于swift,您可以使用下面的代码来修剪video。

 func trimVideo(sourceURL: NSURL, destinationURL: NSURL, trimPoints: TrimPoints, completion: TrimCompletion?) { assert(sourceURL.fileURL) assert(destinationURL.fileURL) let options = [ AVURLAssetPreferPreciseDurationAndTimingKey: true ] let asset = AVURLAsset(URL: sourceURL, options: options) let preferredPreset = AVAssetExportPresetPassthrough if verifyPresetForAsset(preferredPreset, asset) { let composition = AVMutableComposition() let videoCompTrack = composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID()) let audioCompTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID()) let assetVideoTrack: AVAssetTrack = asset.tracksWithMediaType(AVMediaTypeVideo).first as! AVAssetTrack let assetAudioTrack: AVAssetTrack = asset.tracksWithMediaType(AVMediaTypeAudio).first as! AVAssetTrack var compError: NSError? var accumulatedTime = kCMTimeZero for (startTimeForCurrentSlice, endTimeForCurrentSlice) in trimPoints { let durationOfCurrentSlice = CMTimeSubtract(endTimeForCurrentSlice, startTimeForCurrentSlice) let timeRangeForCurrentSlice = CMTimeRangeMake(startTimeForCurrentSlice, durationOfCurrentSlice) videoCompTrack.insertTimeRange(timeRangeForCurrentSlice, ofTrack: assetVideoTrack, atTime: accumulatedTime, error: &compError) audioCompTrack.insertTimeRange(timeRangeForCurrentSlice, ofTrack: assetAudioTrack, atTime: accumulatedTime, error: &compError) if compError != nil { NSLog("error during composition: \(compError)") if let completion = completion { completion(compError) } } accumulatedTime = CMTimeAdd(accumulatedTime, durationOfCurrentSlice) } let exportSession = AVAssetExportSession(asset: composition, presetName: preferredPreset) exportSession.outputURL = destinationURL exportSession.outputFileType = AVFileTypeAppleM4V exportSession.shouldOptimizeForNetworkUse = true removeFileAtURLIfExists(destinationURL) exportSession.exportAsynchronouslyWithCompletionHandler({ () -> Void in if let completion = completion { completion(exportSession.error) } }) } else { NSLog("Could not find a suitable export preset for the input video") let error = NSError(domain: "org.linuxguy.VideoLab", code: -1, userInfo: nil) if let completion = completion { completion(error) } } } 

TrimPoints是CMTime。