#import <AVFoundation/AVFoundation.h>
@interface CustomVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
NSString *_Time;
NSString *_fileName;
NSURL *_outputURL;
NSString *_videoUrl;
}
@property(nonatomic,strong)UIImageView *playImage;
@end
@implementation CustomVC
- (void)viewDidLoad {
[super viewDidLoad];
self.playImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 64, 320, 320)];
[self.view addSubview:self.playImage];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self startvideo];
// [self speakHintMessage];
}
- (void)startvideo {
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera,photoLibrary和photoAlbum
// ipc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所⽀支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie [self presentViewController:ipc animated:YES completion:nil];
// ipc.videoMaximumDuration = 30.0f;// 30秒
ipc.delegate = self;//设置委托
[self presentViewController:ipc animated:YES completion:nil];
}
//此⽅方法可以获取视频⽂文件的时⻓长。
- (CGFloat) getVideoLength:(NSURL *)URL {
AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
CMTime time = [avUrl duration];
int second = ceil(time.value/time.timescale);
return second;
}
//此⽅方法可以获取⽂文件的⼤大⼩小,返回的是单位是KB。
- (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;
}
//完成视频录制,并压缩后显示⼤大⼩小、时⻓长
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"视频文件时长:%f",[self getVideoLength:sourceURL]);
NSString * urlStr = [sourceURL path];
NSLog(@"压缩前视频文件大小:%.2f kb", [self getFileSize:urlStr]);
// self.dateTimeLab.text = [LYWRegex getCurrentTimes];
//获取视频第⼀一帧
self.playImage.image=[self thumbnailImageForVideo:sourceURL atTime:1];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) { //保存视频到相簿,注意也可以使⽤用ALAssetsLibrary来保存
UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
if ([[NSString stringWithFormat:@"%1.f", [self getVideoLength:sourceURL]]integerValue]>300) { [picker dismissViewControllerAnimated:YES completion:nil];
// [MMShowMessage showMessage:@"Video is too long, only 300 seconds"];
}else{
NSURL *newVideoUrl ; //⼀一般.mp4
NSDateFormatter *formater = [[NSDateFormatter alloc] init];//⽤用时间给⽂文件全名,以免重复,在测试的时候其实可以判断⽂文件是否存在若存在,则删除,重新⽣生成⽂文件即可
[formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.MOV", [formater stringFromDate:[NSDate date]]]] ;//这个是保存在app⾃自⼰己的沙盒路路径⾥里里,后⾯面可以选择是否在上传后删除掉。我建议删除掉,免得占空间。
_Time=[formater stringFromDate:[NSDate date]];
_fileName = [NSString stringWithFormat:@"output-%@.MOV", [formater stringFromDate:[NSDate date]]];
NSURL * url = [info objectForKey:UIImagePickerControllerMediaURL];
_outputURL =url;
self.playImage.image =[self getVideoPreViewImage:url];
self.playImage.hidden =NO;
[picker dismissViewControllerAnimated:YES completion:nil];
[self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
} }
}
#pragma mark - 压缩视频
- (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:AVAssetExportPresetLowQuality]; // NSLog(resultPath);
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse= YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void)
{
switch (exportSession.status) {
case AVAssetExportSessionStatusCancelled: NSLog(@"AVAssetExportSessionStatusCancelled"); break;
case AVAssetExportSessionStatusUnknown: NSLog(@"AVAssetExportSessionStatusUnknown"); break;
case AVAssetExportSessionStatusWaiting: NSLog(@"AVAssetExportSessionStatusWaiting"); break;
case AVAssetExportSessionStatusExporting: NSLog(@"AVAssetExportSessionStatusExporting"); break;
case AVAssetExportSessionStatusCompleted: NSLog(@"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->_outputURL = outputURL;
// [self alertUploadVideo:outputURL];
break;
case AVAssetExportSessionStatusFailed: NSLog(@"AVAssetExportSessionStatusFailed"); break;
} }];
}
/**!删除⽂文件隐藏控件 */
-(void)deleteFile {
NSFileManager* fileManager=[NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); //⽂文件名
NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:_fileName];
BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
if (!blHave) {
NSLog(@"no have"); return ;
}else {
NSLog(@" have");
BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
if (blDele) {
self.playImage.image =nil;
self.playImage.hidden =YES;
// self.playBtn.hidden=YES;
// self.deleBtn.hidden =YES;
NSLog(@"dele success");
}else {
NSLog(@"dele fail");
} }
}
#pragma mark - ⾃自定义视频方法
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
// //
if (error) { NSLog(@"保存视频过程中发⽣生错误,错误信息:%@",error.localizedDescription);
} else {
NSLog(@"视频保存成功");
_videoUrl = videoPath;
NSURL * url = [NSURL fileURLWithPath:videoPath];
// self.dateTimeLab.text = [LYWRegex getCurrentTimes]; //获取视频第⼀一帧
// [self.playImage setBackgroundImage: forState:UIControlStateNormal];
self.playImage.image=[self thumbnailImageForVideo:url atTime:1];
_outputURL =url;
self.playImage.image =[self getVideoPreViewImage:url];
}
}
//根据url获取视频的第一帧图片
- (UIImage*) getVideoPreViewImage:(NSURL *)path {
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
assetGen.appliesPreferredTrackTransform = YES;
CMTime time = CMTimeMakeWithSeconds(0.0, 600);
NSError *error = nil;
CMTime actualTime;
CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
return videoImage;
}
//根据url获取视频的第一帧图片
- (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
NSParameterAssert(asset);
AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
assetImageGenerator.appliesPreferredTrackTransform = YES;
assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
CGImageRef thumbnailImageRef = NULL;
CFTimeInterval thumbnailImageTime = time;
NSError *thumbnailImageGenerationError = nil;
thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
if(!thumbnailImageRef)
NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
return thumbnailImage;
}
@end