当我们必须将视频格式从.MOV转换为.MP4​​

时间:2016-07-09 05:45:08

标签: ios objective-c avasset phasset

当我从Gallery中选择一个视频时,我选择的文件扩展名为.MOV,因此想将其转换为.MP4​​,但在这种情况下无法获得如何操作。如果您有任何想法,请帮忙。

  - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
 {


selectedVideoURL = info[UIImagePickerControllerMediaURL];
if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera )
{
    NSURL *videoURL=info[UIImagePickerControllerMediaURL];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
    [library writeVideoAtPathToSavedPhotosAlbum:videoURL completionBlock:^(NSURL *assetURL, NSError *error )
     {
         //here is your URL : assetURL
         NSLog(@"url is%@",assetURL);

         PHFetchResult<PHAsset*> *assets = [PHAsset fetchAssetsWithALAssetURLs:@[assetURL]
                                                                       options:nil];


         PHAsset *asset1 = assets.firstObject;
         [[PHImageManager defaultManager] requestAVAssetForVideo:asset1 options:nil resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
             if ([asset isKindOfClass:[AVURLAsset class]]) {
                 AVURLAsset* urlAsset = (AVURLAsset*)asset;
                 NSNumber *size;

                 [urlAsset.URL getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
                 NSLog(@"size video of camera %f",[size floatValue]/(1024.0*1024.0)); //size is 43.703005
                 NSData *data = [NSData dataWithContentsOfURL:urlAsset.URL];
                 NSLog(@"length of camera %f",[data length]/(1024.0*1024.0)); // data size is 43.703005

                 sizeofVideo=[size floatValue]/(1024.0*1024.0);

                 NSLog(@"sizeofVideo arvin %f",sizeofVideo);
                 if (!sizeofVideo>50.00) {
                     selectedVideoURL=nil;
                     UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Alert" message:@"size of video exist 50MB" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
                     [alert show];

                     attachnoteLbl.text=[NSString stringWithFormat:@"Attach Note:0"];
                 }
                  attachnoteLbl.text=[NSString stringWithFormat:@"Attach Note:1"];

             }
         }];
     }];
}

else

{
    NSURL *videoURL=info[UIImagePickerControllerReferenceURL];
    NSLog(@" valid is%@",[info objectForKey:UIImagePickerControllerReferenceURL]);
    //else this is valid : [info objectForKey:UIImagePickerControllerReferenceURL]];
    PHFetchResult<PHAsset*> *assets = [PHAsset fetchAssetsWithALAssetURLs:@[videoURL]
                                                                  options:nil];


    PHAsset *asset1 = assets.firstObject;


     AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];

    // Check if video is supported for conversion or not
    if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality])
    {
        //Create Export session
        AVAssetExportSession *exportSession = [[AVAssetExportSession       alloc]initWithAsset:avAsset presetName:AVAssetExportPresetLowQuality];

        //Creating temp path to save the converted video
        NSString* documentsDirectory=     [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString* myDocumentPath= [documentsDirectory stringByAppendingPathComponent:@"temp.mp4"];
        NSURL *url = [[NSURL alloc] initFileURLWithPath:myDocumentPath];

        NSData* data = [myDocumentPath dataUsingEncoding:NSUTF8StringEncoding];

        //Check if the file already exists then remove the previous file
        if ([[NSFileManager defaultManager]fileExistsAtPath:myDocumentPath])
        {
            [[NSFileManager defaultManager]removeItemAtPath:myDocumentPath error:nil];
        }
        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;
            }
        }];
    }
    else
    {
        NSLog(@"Video file not supported!");
    }

    [[PHImageManager defaultManager] requestAVAssetForVideo:asset1 options:nil resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
        if ([asset isKindOfClass:[AVURLAsset class]]) {
            AVURLAsset* urlAsset = (AVURLAsset*)asset;
            NSNumber *size;

            [urlAsset.URL getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
            NSLog(@"size video of phassetis %f",[size floatValue]/(1024.0*1024.0)); //size is 43.703005
            NSData *data = [NSData dataWithContentsOfURL:urlAsset.URL];
            NSLog(@"length %f",[data length]/(1024.0*1024.0)); // data size is 43.703005
            sizeofVideo=[size floatValue]/(1024.0*1024.0);

            NSLog(@"sizeofVideo arvin %f",sizeofVideo);
            if (sizeofVideo>50.00) {
                selectedVideoURL=nil;
                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Alert" message:@"size of video exist 50MB" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
                [alert show];
                 attachnoteLbl.text=[NSString stringWithFormat:@"Attach Note:0"];

            }
             attachnoteLbl.text=[NSString stringWithFormat:@"Attach Note:1"];

        }
    }];

}

[picker dismissViewControllerAnimated:YES completion:NULL];
_importView.hidden=YES;

 }

我尝试了以下方法,将.MOV的文件扩展名删除到.MP4,同时上传但是没有工作。所以我认为只需要在从画廊或相机中选择它时才能将其转换为乞讨。但不是如何做到这一点。感谢任何帮助

-(void)afnetworking{

 NSURL *videoURL = [NSURL fileURLWithPath:myDocumentPath];
NSData *data = [NSData dataWithContentsOfURL:videoURL];
if(data)

{

    //     NSString *videoName = [[videoUrl lastPathComponent]stringByDeletingPathExtension];
    NSData *videoData  = [NSData dataWithContentsOfURL:videoURL];
    [bodyData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *tmpfileinfo = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"video_clip\"; filename=\"%@\"\r\n",videoData];
    [bodyData appendData:[tmpfileinfo dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:[NSData dataWithData:videoData]];

}

1 个答案:

答案 0 :(得分:0)

1)首先,你必须从照相馆中选择你已经在做的视频。

2)之后,您必须将所选视频导出到文档目录。

3)然后,您必须在上传到服务器时从文档目录路径中选择视频。

 // Create the asset url with the video file
        AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
        NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];

        // Check if video is supported for conversion or not
        if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality])
        {
        //Create Export session
             AVAssetExportSession *exportSession = [[AVAssetExportSession       alloc]initWithAsset:avAsset presetName:AVAssetExportPresetLowQuality];

        //Creating temp path to save the converted video
             NSString* documentsDirectory=     [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
             NSString* myDocumentPath= [documentsDirectory stringByAppendingPathComponent:@"temp.mp4"];
             NSURL *url = [[NSURL alloc] initFileURLWithPath:myDocumentPath];

        //Check if the file already exists then remove the previous file
             if ([[NSFileManager defaultManager]fileExistsAtPath:myDocumentPath])
             {
                  [[NSFileManager defaultManager]removeItemAtPath:myDocumentPath error:nil];
             }
             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;
              }
             }];
        }
        else
        {
               NSLog(@"Video file not supported!");
        }

修改

-(void)afnetworking{
NSUrl *videoURL = [NSURL fileURLWithPath:myDocumentPath];
NSData *data = [NSData dataWithContentsOfURL:videoURL];
   if(data)
{
    NSString *videoName = [[videoUrl lastPathComponent]stringByDeletingPathExtension];
    NSData *videoData  = [NSData dataWithContentsOfURL:selectedVideoURL];
    [bodyData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *tmpfileinfo = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"video_clip\"; filename=\"%@.mp4\"\r\n",videoName];
    [bodyData appendData:[tmpfileinfo dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:[NSData dataWithData:videoData]];

}