#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
AVPlayerViewControllerDelegate
{
AVPlayerViewController *mPMoviePlayerViewController;
}
//调用系统详解
UIImagePickerController *pickerCon = [[UIImagePickerController alloc]init];
pickerCon.sourceType = UIImagePickerControllerSourceTypeCamera;
pickerCon.mediaTypes = @[(NSString *)kUTTypeMovie];//设定相机为视频
pickerCon.cameraDevice = UIImagePickerControllerCameraDeviceRear;//设置相机后摄像头
pickerCon.videoMaximumDuration = 10;//最长拍摄时间
pickerCon.videoQuality = UIImagePickerControllerQualityTypeIFrame960x540;//拍摄质量
pickerCon.allowsEditing = YES;//是否可编辑
pickerCon.delegate = self;
[self presentViewController:pickerCon animated:YES completion:nil];
//代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
//以下均是在使用摄像头拍照情况下,在使用相册或图库功能时大致相同
// 获取媒体类型信息
NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
//如果是拍照
UIImage *image;
//如果允许编辑则获得编辑后的照片,否则获取原始照片
if (picker.allowsEditing) {
image=[info objectForKey:UIImagePickerControllerEditedImage];//获取编辑后的照片
}else{
image=[info objectForKey:UIImagePickerControllerOriginalImage];
//获取原始照片
}
/* CGRect cropRect = [[info objectForKey:UIImagePickerControllerCropRect] CGRectValue]; UIImage * cropImage=[info objectForKey:UIImagePickerControllerOriginalImage]; UIImage *rotatedOriginalImage = [cropImage imageRotatedByDegrees:90.0]; CGImageRef imageRef = CGImageCreateWithImageInRect(rotatedOriginalImage.CGImage, cropRect); UIImage * resultImage = [UIImage imageWithCGImage:imageRef]; //以此法获得的图片即为编辑后的图片其中-imageRotatedByDegrees: 方法是将图片顺时针转动90度的方法 */
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image: didFinishSavingWithError: contextInfo:), nil);
// 若保存到相簿后没有其他操作可以:UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}else if([mediaType isEqualToString:(NSString *)kUTTypeMovie]){//如果是录制视频
NSURL *url=[info objectForKey:UIImagePickerControllerMediaURL];//视频路径
NSString *urlStr=[url path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
//保存视频到相簿,注意也可以使用ALAssetsLibrary来保存
UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);//保存视频到相簿
000
_videoURL = url;
_collectionView.hidden = YES;
self.backgroundIV.hidden = NO;
self.playBtn.hidden = NO;
self.backgroundIV.image= [self getImage:[[_videoURL absoluteString ] stringByReplacingOccurrencesOfString:@"file://" withString:@""]];
aVideoUrlForPlay = [NSString stringWithFormat:@"%@", _videoURL];
NSLog(@"压缩前视频时长=%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:url]]);
NSLog(@"压缩前视频大小=%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[url path]]]);
NSURL *newVideoUrl ; //一般.mp4
NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名,以免重复,在测试的时候其实可以判断文件是否存在若存在,则删除,重新生成文件即可
[formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//这个是保存在app自己的沙盒路径里,后面可以选择是否在上传后删除掉。我建议删除掉,免得占空间。
[self convertVideoQuailtyWithInputURL:url outputURL:newVideoUrl completeHandler:nil];
// NSData *data = [NSData dataWithContentsOfFile:[url absoluteString]];
// NSData *data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@", [[_videoURL absoluteString ] stringByReplacingOccurrencesOfString:@"file://" withString:@""]]];
}
}
[picker dismissViewControllerAnimated:YES completion:^{ }];
}
//压缩
- (void) convertVideoQuailtyWithInputURL:(NSURL*)inputURL
outputURL:(NSURL*)outputURL
completeHandler:(void (^)(AVAssetExportSession*))handler{
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse= YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void){
switch (exportSession.status) {
case AVAssetExportSessionStatusCancelled:
break;
case AVAssetExportSessionStatusUnknown:
break;
case AVAssetExportSessionStatusWaiting:
break;
case AVAssetExportSessionStatusExporting:
break;
case AVAssetExportSessionStatusCompleted:
NSLog(@"压缩后时长%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
NSLog(@"压缩后大小%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);
UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册
[self alertUploadVideo:outputURL];
break;
case AVAssetExportSessionStatusFailed:
break;
}
}];
}
//上传提示
-(void)alertUploadVideo:(NSURL*)URL{
_videoURL = URL;
CGFloat size = [self getFileSize:[URL path]];
NSString *message;
NSString *sizeString;
CGFloat sizemb= size/1024;
if(size <= 1024){
sizeString = [NSString stringWithFormat:@"%.2fKB",size];
}else{
sizeString = [NSString stringWithFormat:@"%.2fMB",sizemb];
}
if(sizemb < 2){
[self changeUserVideoView:URL];
}else if(sizemb<=5){
message = [NSString stringWithFormat:@"视频%@,大于2MB会有点慢,确定上传吗?", sizeString];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:message message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[alertView show];
}else if(sizemb>5){
message = [NSString stringWithFormat:@"视频%@,超过5MB,不能上传,抱歉。", sizeString];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:message message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
[alertView show];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
[[NSFileManager defaultManager] removeItemAtPath:[_videoURL path] error:nil];//取消之后就删除,以免占用手机硬盘空间
}else{
[self changeUserVideoView:_videoURL];
}
}
//上传视频
- (void)changeUserVideoView:(NSURL *)url{
NSData *data = [NSData dataWithContentsOfURL:url];
// NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
self.navigationItem.rightBarButtonItem.enabled = YES;
NSMutableDictionary *viedoExparams = [[NSMutableDictionary alloc]init];
[viedoExparams addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:data,@"pic",nil]];
[CKHttpCommunicate createRequest:HTTP_upload2Tmp WithParam:nil withExParam:viedoExparams withMethod:POST success:^(id result) {
_selectedVideodWithImagrUrl = [NSString stringWithFormat:@"%@",result[@"d"]];
if (_selectedVideodWithImagrUrl != nil) {
[MBProgressHUD hideHUDForView:self.view animated:nil];
self.navigationItem.rightBarButtonItem.enabled = YES;
}
} uploadFileProgress:^(NSProgress *uploadProgress) {
} failure:^(NSError *erro) {
}];
}
- (CGFloat) getFileSize:(NSString *)path
{
NSLog(@"%@",path);
NSFileManager *fileManager = [NSFileManager defaultManager];
float filesize = -1.0;
if ([fileManager fileExistsAtPath:path]) {
NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
filesize = 1.0*size/1024;
}else{
NSLog(@"找不到文件");
}
return filesize;
}//此方法可以获取文件的大小,返回的是单位是KB。
- (CGFloat) getVideoLength:(NSURL *)URL
{
AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
CMTime time = [avUrl duration];
int second = ceil(time.value/time.timescale);
return second;
}//此方法可以获取视频文件的时长。
// 照片保存到相簿的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
NSLog(@"保存照片过程中发生错误,错误信息:%@",error.localizedDescription);
}else{
NSLog(@"照片保存成功.");
}
}
// 视频保存到相簿的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
NSLog(@"保存视频过程中发生错误,错误信息:%@",error.localizedDescription);
}else{
NSLog(@"视频保存成功.");
//录制完之后可以使用AVPlayer自动播放
NSURL *url=[NSURL fileURLWithPath:videoPath];
NSLog(@"视频路径=%@", url);
}
}
//上传完毕后播放视频方法
- (void)addPlayerView {
// EditVideoViewController* cor = [[EditVideoViewController alloc] init];
// cor.videoURL = _videoURL;
// cor.isyulan = @"1";
// [self pushViewController:cor animated:YES];
// 2、初始化媒体播放控制器
if (mPMoviePlayerViewController) {
mPMoviePlayerViewController = nil;
}
// 3、配置媒体播放控制器
mPMoviePlayerViewController = [[AVPlayerViewController alloc] init];
// 设置媒体源数据
mPMoviePlayerViewController.player = [AVPlayer playerWithURL:_videoURL];
// 设置拉伸模式
mPMoviePlayerViewController.videoGravity = AVLayerVideoGravityResizeAspect;
// 设置是否显示媒体播放组件
mPMoviePlayerViewController.showsPlaybackControls = YES;
// 设置代理
mPMoviePlayerViewController.delegate = self;
// 播放视频
[mPMoviePlayerViewController.player play];
// 设置媒体播放器视图大小
// mPMoviePlayerViewController.view.bounds = CGRectMake(0, 0, 350, 300);
// mPMoviePlayerViewController.view.center = CGPointMake(CGRectGetMidX(self.view.bounds), 64 + CGRectGetMidY(mPMoviePlayerViewController.view.bounds) + 30);
// 4、推送播放
// 推送至媒体播放器进行播放
[self presentViewController:mPMoviePlayerViewController animated:YES completion:nil];
// 直接在本视图控制器播放
// [self addChildViewController:mPMoviePlayerViewController];
// [self.view addSubview:mPMoviePlayerViewController.view];
}