iOS压缩本地相册视频

2016-07-22  本文已影响679人  captain_Lu

前言

读取iphone本地相册中的视频文件路径:assets-library://asset/asset.mov?id=xxxxxxxx-xxxxx-xxxx-xxxx-xxxxxxxxxxx&ext=mov形式
可以使用这种路径进行视频播放等操作,但不能用于视频上传,意思就是不能用于数据传输的载体,因此如果需要上传到服务器,需要读取-压缩-写入沙盒三部。

NSString * saveVideopath = [NSString stringWithFormat:@"%@/Library/NBCache/%@/SaveVideo/",NSHomeDirectory(),@"123456789"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:saveVideopath])
        {
            NSError * error = nil;
            if ([[NSFileManager defaultManager] createDirectoryAtPath:saveVideopath withIntermediateDirectories:YES attributes:nil error:&error]){
            }
            else
            {
                NSLog(@"%@",error);
            }
        }
    NSString * videoOutputPath = [NSString stringWithFormat:@"%@%@.mp4",videoSavePath,[[NSString stringWithFormat:@"%@",url] md5]];
    __weak typeof(self)weakSelf = self;
    if (![[NSFileManager defaultManager] fileExistsAtPath:videoOutputPath])//如果沙盒中没有则进行压缩
    {
        AVURLAsset * urlAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
        AVAssetExportSession * exportSession = [AVAssetExportSession exportSessionWithAsset:urlAsset presetName:AVAssetExportPresetMediumQuality];
        exportSession.outputFileType = AVFileTypeMPEG4;
        exportSession.outputURL = [NSURL fileURLWithPath:videoOutputPath];
        NSLog(@"开始压缩");
        self.onCompress = YES;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch (exportSession.status)
            {
                case AVAssetExportSessionStatusUnknown:{
                    }
                    break;
                }
                case AVAssetExportSessionStatusWaiting:{
                    }
                    break;
                }
                case AVAssetExportSessionStatusExporting:{
                    }
                    break;
                }
                case AVAssetExportSessionStatusCompleted:{
                    break;
                }
                case AVAssetExportSessionStatusFailed:{
                    }
                    break;
                }
                case AVAssetExportSessionStatusCancelled:{
                    }
                    break;
                }
                default:
                    break;
            }
        }];
    } else {//沙盒中直接获取
        [weakSelf videoHasExist:url filePath:videoOutputPath];
    }

详细代码参见本人github上的(示例工程)[https://github.com/captain-Lu/KLVideoCompressTool];

上一篇下一篇

猜你喜欢

热点阅读