我想修剪視頻文件。我只想從圖庫中挑選視頻並將其轉換爲15秒的視頻。對於Objective C,我正在關注thislink。它對我來說工作正常,但我是Swift語言的初學者。任何人都可以幫助我在Swift中轉換此代碼嗎?如何修剪視頻文件並使用Swift轉換爲20秒視頻?
下面是我的目標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 :)");
}
}];
}
讀者很樂意幫助將代碼從X轉換爲Y,但是海報_must_首先對它進行了誠實的嘗試。這裏根本沒有證據證明這一點,所以我正在進行近距離投票。在發佈問題之前,請務必付出努力!謝謝。 – halfer