//完成視頻錄制扣汪,并壓縮后顯示大小攻臀、時長
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
isSelectImg=YES;
NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[sourceURL 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自己的沙盒路徑里棺妓,后面可以選擇是否在上傳后刪除掉攘已。我建議刪除掉,免得占空間涧郊。
[picker dismissViewControllerAnimated:YES completion:nil];
[self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
}
- (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];
//? 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]]]);
break;
case AVAssetExportSessionStatusFailed:
NSLog(@"AVAssetExportSessionStatusFailed");
break;
}
}];
}
- (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;
}