2010-12-14 14 views
9

Puedo grabar el video usando AVFoundation o UIImagePickerController. Pero no puedo recortar el video de un segundo en particular a otra duración/tiempo en particular. Alguien puede ayudarme.Cómo recortar el video usando AVFoundation

Gracias, Siva Krishna.

+0

encontrado esta pregunta, mientras que en busca de algo para recortar un vídeo existente. Recortar videos capturados es relativamente sencillo. Pero parece que me sale la ventana de Trim. Espero que mi respuesta a continuación ayude. –

Respuesta

18

Puede tener la UIImagePickerController permiten recortar

UIImagePickerController *videoRecorder = [[UIImagePickerController alloc]init];   
     NSArray *sourceTypes = [UIImagePickerController availableMediaTypesForSourceType:videoRecorder.sourceType]; 
     NSLog(@"Available types for source as camera = %@", sourceTypes); 
     if (![sourceTypes containsObject:(NSString*)kUTTypeMovie]) { 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                  message:@"Device Not Supported for video Recording."                  delegate:self 
                cancelButtonTitle:@"Yes" 
                otherButtonTitles:@"No",nil]; 
      [alert show]; 
      [alert release]; 
      return; 
     } 
     videoRecorder.allowsEditing = YES; 

Desafortunadamente después de volver de la imagePickerController, que se ven obligados a convertir el vídeo de forma manual.

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{ 
    if ([self.popoverLibraryBrowser isPopoverVisible]) 
    { 
     [self.popoverLibraryBrowser dismissPopoverAnimated:YES]; 
    } 
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType]; 
    if ([type isEqualToString:(NSString *)kUTTypeVideo] || 
     [type isEqualToString:(NSString *)kUTTypeMovie]) { // movie != video 
     NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; 


     NSNumber *start = [info objectForKey:@"_UIImagePickerControllerVideoEditingStart"]; 
     NSNumber *end = [info objectForKey:@"_UIImagePickerControllerVideoEditingEnd"]; 

     // if start and end are nil then clipping was not used. 
     // You should use the entire video. 


     int startMilliseconds = ([start doubleValue] * 1000); 
     int endMilliseconds = ([end doubleValue] * 1000); 

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 

     NSFileManager *manager = [NSFileManager defaultManager]; 

     NSString *outputURL = [documentsDirectory stringByAppendingPathComponent:@"output"] ; 
     [manager createDirectoryAtPath:outputURL withIntermediateDirectories:YES attributes:nil error:nil]; 

     outputURL = [outputURL stringByAppendingPathComponent:@"output.mp4"]; 
     // Remove Existing File 
     [manager removeItemAtPath:outputURL error:nil]; 


     //[self loadAssetFromFile:videoURL]; 

     [self.recorder dismissModalViewControllerAnimated:YES]; 

     AVURLAsset *videoAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil]; 


     AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:videoAsset presetName:AVAssetExportPresetHighestQuality]; 
     exportSession.outputURL = [NSURL fileURLWithPath:outputURL]; 
     exportSession.outputFileType = AVFileTypeQuickTimeMovie; 
     CMTimeRange timeRange = CMTimeRangeMake(CMTimeMake(startMilliseconds, 1000), CMTimeMake(endMilliseconds - startMilliseconds, 1000)); 
     exportSession.timeRange = timeRange; 

     [exportSession exportAsynchronouslyWithCompletionHandler:^{ 
      switch (exportSession.status) { 
       case AVAssetExportSessionStatusCompleted: 
        // Custom method to import the Exported Video 
        [self loadAssetFromFile:exportSession.outputURL]; 
        break; 
       case AVAssetExportSessionStatusFailed: 
        // 
        NSLog(@"Failed:%@",exportSession.error); 
        break; 
       case AVAssetExportSessionStatusCancelled: 
        // 
        NSLog(@"Canceled:%@",exportSession.error); 
        break; 
       default: 
        break; 
      } 
     }]; 



     //NSData *videoData = [NSData dataWithContentsOfURL:videoURL]; 
     //NSString *videoStoragePath;//Set your video storage path to this variable 
     //[videoData writeToFile:videoStoragePath atomically:YES]; 
     //You can store the path of the saved video file in sqlite/coredata here. 
    } 
} 
+0

Gracias por la fuente. Cuando uso "* sourceTypes" como "UIImagePickerControllerSourceTypeCamera", obtengo "* start y * end time". Pero cuando uso "* sourceTypes" como "UIImagePickerControllerSourceTypeSavedPhotosAlbum", no obtengo el tiempo de "inicio y fin". ¿Cuál es el problema? ¿Cómo puedo obtener el tiempo de "inicio y fin"? – SKK

+0

¿Les diste la posibilidad de "recortar" el video? La parte que completa el inicio y el final de la edición es el recorte. Si no recorta el video, estos valores se dejan nulos, lo que a su vez significa que se debe omitir el recorte y se debe usar todo el video. –

+0

Consulte el registro aquí http://pastebin.com/uMU1k61T. Permitiré al usuario seleccionar los marcos de la miniatura. No hay problema, si edito la "Cámara de video grabada" y el problema ocurre cuando intento seleccionar los fotogramas de los videos cargados desde el álbum. – SKK

0

debe agregar kUTTypeMovie en la matriz setMediaTypes y funcionará.

2

versión anterior de Swift

import UIKit 
import AVFoundation 
import MobileCoreServices 

func pickVideo(){ 
    if UIImagePickerController.isSourceTypeAvailable(.Camera) { 
     let videoRecorder = UIImagePickerController() 
     videoRecorder.sourceType = .Camera 
     videoRecorder.mediaTypes = [kUTTypeMovie as String] 
     videoRecorder.allowsEditing = true 
     videoRecorder.delegate = self 

     presentViewController(videoRecorder, animated: true, completion: nil) 
    } 
} 


func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { 
    picker.dismissViewControllerAnimated(true, completion: nil) 
    let manager = NSFileManager.defaultManager() 

    guard let documentDirectory = try? manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) else {return} 
    guard let mediaType = info[UIImagePickerControllerMediaType] as? String else {return} 
    guard let url = info[UIImagePickerControllerMediaURL] as? NSURL else {return} 

    if mediaType == kUTTypeMovie as String || mediaType == kUTTypeVideo as String { 
     let asset = AVAsset(URL: url) 
     let length = Float(asset.duration.value)/Float(asset.duration.timescale) 
     print("video length: \(length) seconds") 

     let start = info["_UIImagePickerControllerVideoEditingStart"] as? Float 
     let end = info["_UIImagePickerControllerVideoEditingEnd"] as? Float 


     var outputURL = documentDirectory.URLByAppendingPathComponent("output") 


     do { 
      try manager.createDirectoryAtURL(outputURL, withIntermediateDirectories: true, attributes: nil) 
      outputURL = outputURL.URLByAppendingPathComponent("output.mp4") 
     }catch let error { 
      print(error) 
     } 

     //Remove existing file 
     _ = try? manager.removeItemAtURL(outputURL) 


     guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) else {return} 
     exportSession.outputURL = outputURL 
     exportSession.outputFileType = AVFileTypeMPEG4 

     let startTime = CMTime(seconds: Double(start ?? 0), preferredTimescale: 1000) 
     let endTime = CMTime(seconds: Double(end ?? length), preferredTimescale: 1000) 
     let timeRange = CMTimeRange(start: startTime, end: endTime) 

     exportSession.timeRange = timeRange 
     exportSession.exportAsynchronouslyWithCompletionHandler{ 
      switch exportSession.status { 
      case .Completed: 
       print("exported at \(outputURL)") 

      case .Failed: 
       print("failed \(exportSession.error)") 

      case .Cancelled: 
       print("cancelled \(exportSession.error)") 

      default: break 
      } 
     } 
    } 
} 
+0

gracias por este método funcionó como se esperaba ... –

Cuestiones relacionadas