2011-12-12 41 views
21

Tôi đang phát triển máy chủ phương tiện cho Play station 3 trong iPhone.MOV để chuyển đổi video Mp4 iPhone Lập trình

Tôi biết rằng PS3 không hỗ trợ tệp .MOV vì vậy tôi phải chuyển đổi nó thành Mp4 hoặc một số mã chuyển tiếp khác mà PS3 hỗ trợ.

Đây là những gì tôi đã làm nhưng nó bị treo nếu tôi đặt loại tệp khác với tệp nguồn của nó.

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

      NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset]; 

      if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) 

      { 

       AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetLowQuality]; 

       exportSession.outputURL = [NSURL fileURLWithPath:videoPath]; 

       exportSession.outputFileType = AVFileTypeMPEG4; 

       CMTime start = CMTimeMakeWithSeconds(1.0, 600); 

       CMTime duration = CMTimeMakeWithSeconds(3.0, 600); 

       CMTimeRange range = CMTimeRangeMake(start, duration); 

       exportSession.timeRange = range; 

       [exportSession exportAsynchronouslyWithCompletionHandler:^{ 

        switch ([exportSession status]) { 

         case AVAssetExportSessionStatusFailed: 
          NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]); 

          break; 

         case AVAssetExportSessionStatusCancelled: 

          NSLog(@"Export canceled"); 

          break; 

         default: 

          break; 

        } 

        [exportSession release]; 

       }]; 

      } 

Nếu tôi đặt AVFileTypeMPEG4 ở đây thì nó đổ vỡ, nói "Loại tệp không hợp lệ". Vì vậy, tôi phải thiết lập nó để AVFileTypeQuickTimeMovie và nó mang lại cho tập tin MOV.

Có thể trong iOS chuyển đổi video từ MOV sang Mp4 thông qua AVAssetExportSession ... HOẶC không có thư viện Thirdparty nào không?

+0

Bạn đã bao giờ nhận được một giải pháp cho việc này? – newenglander

+0

Bạn có giải pháp cho chuyển đổi này không ??? – svmrajesh

+0

Bạn không thể đọc bất kỳ codec .mov ngẫu nhiên nào trên iOS, chỉ có video h.264 được mã hóa dưới dạng .mov/.m4v có thể đọc được bằng AVFoundation. – MoDJ

Trả lời

7

MOV rất giống với MP4, bạn có thể chỉ cần thay đổi phần mở rộng và làm việc, Windows Phone không thể phát .MOVS nhưng có thể chơi mp4, tất cả những gì tôi đã làm để làm việc đó là thay đổi phần mở rộng. mov để .mp4 và nó hoạt động tốt, và điều này là từ video bắn trên iphone ... và nếu bất cứ điều gì bạn có thể def thử xuất khẩu với AVAssetExporter và thử có một loại tập tin trong đó cho MP4 và M4A như bạn có thể nhìn thấy từ fileformat UTIs here

hy vọng nó sẽ giúp

+0

Daniel, dưới đây là những gì tôi đã làm nhưng nó bị treo nếu tôi đặt loại tệp khác với tệp nguồn của nó. –

+2

Thay đổi phần mở rộng thành mp4 không hoạt động với tôi –

+7

Nó không hoạt động ở mọi nơi mà giải pháp, ví dụ một số thiết bị Android không sao chép các video này – Kasas

10

presetName sử dụng "AVAssetExportPresetPassthrough" thay vì "AVAssetExportPresetLowQuality"

AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetPassthrough]; 
2

chỉ muốn nói rằng URL không thể như

[NSURL URLWithString: [@"~/Documents/movie.mov" stringByExpandingTildeInPath]] 

Nó phải là như

[NSURL fileURLWithPath: [@"~/Documents/movie.mov" stringByExpandingTildeInPath]] 

Đã cho tôi một thời gian để con số đó ra :-)

+0

Cảm ơn bạn rất nhiều –

3

Sử dụng mã bên dưới

NSURL * mediaURL = [info objectForKey:UIImagePickerControllerMediaURL]; 
    AVAsset *video = [AVAsset assetWithURL:mediaURL]; 
    AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:video presetName:AVAssetExportPresetMediumQuality]; 
    exportSession.shouldOptimizeForNetworkUse = YES; 
    exportSession.outputFileType = AVFileTypeMPEG4; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; 
    basePath = [basePath stringByAppendingPathComponent:@"videos"]; 
    if (![[NSFileManager defaultManager] fileExistsAtPath:basePath]) 
     [[NSFileManager defaultManager] createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil]; 

    compressedVideoUrl=nil; 
    compressedVideoUrl = [NSURL fileURLWithPath:basePath]; 
    long CurrentTime = [[NSDate date] timeIntervalSince1970]; 
    NSString *strImageName = [NSString stringWithFormat:@"%ld",CurrentTime]; 
    compressedVideoUrl=[compressedVideoUrl URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",strImageName]]; 

    exportSession.outputURL = compressedVideoUrl; 

    [exportSession exportAsynchronouslyWithCompletionHandler:^{ 

     NSLog(@"done processing video!"); 
     NSLog(@"%@",compressedVideoUrl); 

     if(!dataMovie) 
      dataMovie = [[NSMutableData alloc] init]; 
     dataMovie = [NSData dataWithContentsOfURL:compressedVideoUrl]; 

    }]; 
5

Bạn cần AVMutableComposition để thực hiện việc này. Bởi vì Asset không thể chuyển mã sang MP4 trực tiếp trong iOS 5.0.

- (BOOL)encodeVideo:(NSURL *)videoURL 
{ 
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil]; 

    // Create the composition and tracks 
    AVMutableComposition *composition = [AVMutableComposition composition]; 
    AVMutableCompositionTrack *videoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid]; 
    AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid]; 
    NSArray *assetVideoTracks = [asset tracksWithMediaType:AVMediaTypeVideo]; 
    if (assetVideoTracks.count <= 0) 
    { 
      NSLog(@"Error reading the transformed video track"); 
      return NO; 
    } 

    // Insert the tracks in the composition's tracks 
    AVAssetTrack *assetVideoTrack = [assetVideoTracks firstObject]; 
    [videoTrack insertTimeRange:assetVideoTrack.timeRange ofTrack:assetVideoTrack atTime:CMTimeMake(0, 1) error:nil]; 
    [videoTrack setPreferredTransform:assetVideoTrack.preferredTransform]; 

    AVAssetTrack *assetAudioTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]; 
    [audioTrack insertTimeRange:assetAudioTrack.timeRange ofTrack:assetAudioTrack atTime:CMTimeMake(0, 1) error:nil]; 

    // Export to mp4 
    NSString *mp4Quality = [MGPublic isIOSAbove:@"6.0"] ? AVAssetExportPresetMediumQuality : AVAssetExportPresetPassthrough; 
    NSString *exportPath = [NSString stringWithFormat:@"%@/%@.mp4", 
            [NSHomeDirectory() stringByAppendingString:@"/tmp"], 
            [BSCommon uuidString]]; 

    NSURL *exportUrl = [NSURL fileURLWithPath:exportPath]; 
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:mp4Quality]; 
    exportSession.outputURL = exportUrl; 
    CMTime start = CMTimeMakeWithSeconds(0.0, 0); 
    CMTimeRange range = CMTimeRangeMake(start, [asset duration]); 
    exportSession.timeRange = range; 
    exportSession.outputFileType = AVFileTypeMPEG4; 
    [exportSession exportAsynchronouslyWithCompletionHandler:^{ 
      switch ([exportSession status]) 
      { 
       case AVAssetExportSessionStatusCompleted: 
         NSLog(@"MP4 Successful!"); 
         break; 
       case AVAssetExportSessionStatusFailed: 
         NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]); 
         break; 
       case AVAssetExportSessionStatusCancelled: 
         NSLog(@"Export canceled"); 
         break; 
       default: 
         break; 
      } 
    }]; 

    return YES; 
} 
+0

là công trình này cho tất cả các định dạng hoặc chỉ .mov ?? – yazh

5

Bạn có thể chuyển đổi video bằng mp4 bằng AVAssets.

AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil]; 
NSArray *compatiblePresets = [AVAssetExportSession  
exportPresetsCompatibleWithAsset:avAsset]; 
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetLowQuality]; 

NSString* documentsDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    exportSession.outputURL = url; 
//set the output file format if you want to make it in other file format (ex .3gp) 
exportSession.outputFileType = AVFileTypeMPEG4; 
exportSession.shouldOptimizeForNetworkUse = YES; 

[exportSession exportAsynchronouslyWithCompletionHandler:^{ 
switch ([exportSession status]) 
{ 
     case AVAssetExportSessionStatusFailed: 
      NSLog(@"Export session failed"); 
      break; 
     case AVAssetExportSessionStatusCancelled: 
      NSLog(@"Export canceled"); 
      break; 
     case AVAssetExportSessionStatusCompleted: 
     { 
      //Video conversion finished 
      NSLog(@"Successful!"); 
     } 
      break; 
     default: 
      break; 
    } 
}]; 

Để dễ dàng chuyển đổi video sang mp4 sử dụng này link.

Bạn cũng có thể tìm dự án mẫu để chuyển đổi video thành mp4.

+0

Tệp đầu ra có thể là đối tượng '' 'NSData''' tạm thời thay vì' '' outputURL''' không? Tôi không hiểu nơi tôi phải lưu tập tin chuyển đổi .... và nhiều hơn nữa đến mức tôi không muốn lưu nó, tôi chỉ muốn tải nó lên một máy chủ, vì vậy tôi không cần '' 'outputURL''', tôi chỉ cần xuất nó vào một đối tượng. – Supertecnoboff

4

Đây là mã

func encodeVideo(videoURL: NSURL) { 
    let avAsset = AVURLAsset(URL: videoURL, options: nil) 

    var startDate = NSDate() 

    //Create Export session 
    exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough) 

    // exportSession = AVAssetExportSession(asset: composition, presetName: mp4Quality) 
    //Creating temp path to save the converted video 


    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] 
    let myDocumentPath = NSURL(fileURLWithPath: documentsDirectory).URLByAppendingPathComponent("temp.mp4").absoluteString 
    let url = NSURL(fileURLWithPath: myDocumentPath) 

    let documentsDirectory2 = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL 

    let filePath = documentsDirectory2.URLByAppendingPathComponent("rendered-Video.mp4") 
    deleteFile(filePath) 

    //Check if the file already exists then remove the previous file 
    if NSFileManager.defaultManager().fileExistsAtPath(myDocumentPath) { 
     do { 
      try NSFileManager.defaultManager().removeItemAtPath(myDocumentPath) 
     } 
     catch let error { 
      print(error) 
     } 
    } 

    url 

    exportSession!.outputURL = filePath 
    exportSession!.outputFileType = AVFileTypeMPEG4 
    exportSession!.shouldOptimizeForNetworkUse = true 
    var start = CMTimeMakeWithSeconds(0.0, 0) 
    var range = CMTimeRangeMake(start, avAsset.duration) 
    exportSession.timeRange = range 

    exportSession!.exportAsynchronouslyWithCompletionHandler({() -> Void in 
     switch self.exportSession!.status { 
     case .Failed: 
      print("%@",self.exportSession?.error) 
     case .Cancelled: 
      print("Export canceled") 
     case .Completed: 
      //Video conversion finished 
      var endDate = NSDate() 

      var time = endDate.timeIntervalSinceDate(startDate) 
      print(time) 
      print("Successful!") 
      print(self.exportSession.outputURL) 

     default: 
      break 
     } 

    }) 


} 

func deleteFile(filePath:NSURL) { 
    guard NSFileManager.defaultManager().fileExistsAtPath(filePath.path!) else { 
     return 
    } 

    do { 
     try NSFileManager.defaultManager().removeItemAtPath(filePath.path!) 
    }catch{ 
     fatalError("Unable to delete file: \(error) : \(__FUNCTION__).") 
    } 
} 
Các vấn đề liên quan