2015-06-26 114 views
2

我想修剪視頻文件。我只想從圖庫中挑選視頻並將其轉換爲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 :)"); 
     } 

    }]; 


} 
+0

讀者很樂意幫助將代碼從X轉換爲Y,但是海報_must_首先對它進行了誠實的嘗試。這裏根本沒有證據證明這一點,所以我正在進行近距離投票。在發佈問題之前,請務必付出努力!謝謝。 – halfer

回答

3

的SWIFT,您可以使用下面的代碼進行修整視頻。

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。

+0

hi @Vishnu Kumar。 S我已經實現了上面的代碼,但得到同樣的錯誤,因爲我在這裏描述http://stackoverflow.com/questions/31163082/video-trimming-failed-with-block-avassetexportsessionstatus-failed – Rock

+0

我用這個和它的工作幾乎完美。除2個問題外, 1>當視頻具有多於一個分割時,某些加入顯示幾秒鐘的黑屏 2>最終視頻沒有音頻。 這些問題隨機出現。 –