需要導(dǎo)入:#import <AVFoundation/AVFoundation.h>
使用到的變量:
@property (nonatomic, strong) NSString * videoPath;//視頻壓縮處理后的路徑
@property (nonatomic, strong) NSString * qualityPreset; //預(yù)設(shè)視頻壓縮畫質(zhì)
代碼調(diào)用方式:
[self alertVideoHandleModel];
核心代碼展示:
- (void)alertVideoHandleModel {
UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"視頻選擇" message:@"您可在相冊(cè)中選擇視頻,也可以直接錄制視頻" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *chooseVideoAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self chooseVideo];
}];
UIAlertAction *recordVideoAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self startRecordVideo];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[actionSheet addAction:chooseVideoAction];
[actionSheet addAction:recordVideoAction];
[actionSheet addAction:cancelAction];
[self presentViewController:actionSheet animated:YES completion:nil];
}
#pragma mark *** Video Handling -------------- Start -------------- ***
// 選擇本地視頻
- (void)chooseVideo {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
[self presentViewController:imagePicker animated:YES completion:nil];
imagePicker.delegate = self;
}
// 錄制視頻
- (void)startRecordVideo {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
[self presentViewController:imagePicker animated:YES completion:nil];
// 最長(zhǎng)拍攝 300秒(5分鐘)
imagePicker.videoMaximumDuration = 5.0 * 60.0f;
imagePicker.delegate = self;
}
// 獲取文件的大小,返回的是單位是MB。
- (CGFloat)getFileSize:(NSString *)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/1024;
} else {
NSLog(@"沒有找到相關(guān)文件");
}
return filesize;
}
// 獲取視頻文件的時(shí)長(zhǎng)。
- (CGFloat)getVideoLength:(NSURL *)URL {
AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
CMTime time = [avUrl duration];
int second = ceil(time.value / time.timescale);
return second;
}
// 獲取視頻第一幀圖片
- (UIImage *)getFirstFrameWithVideoURL:(NSURL *)URL {
NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:URL options:opts];
AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
generator.appliesPreferredTrackTransform = YES;
generator.maximumSize = CGSizeMake(400, 200);
NSError *error = nil;
CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
if (!error) {
return [UIImage imageWithCGImage:img];
}
return nil;
}
// 刪除導(dǎo)出后的視頻
- (void)removeWithVideoPath:(NSString *)path {
// 刪除文件
BOOL isDelete = [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
if (!isDelete) {
NSLog(@"視頻刪除失敗");
}
}
#pragma mark - <UIImagePickerControllerDelegate>
// 完成視頻錄制,并壓縮后顯示大小、時(shí)長(zhǎng)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// 拿到視頻地址
NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
// 將視頻第一幀圖片賦值給按鈕
[self.addVedioBtn setImage:[self getFirstFrameWithVideoURL:sourceURL] forState:UIControlStateNormal];
CGFloat videoSize = [self getFileSize:[sourceURL path]];
NSLog(@"壓縮處理之前的視頻時(shí)長(zhǎng):%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
NSLog(@"壓縮處理之前的視頻大小:%@", [NSString stringWithFormat:@"%.2f MB", videoSize]);
// 預(yù)設(shè)壓縮質(zhì)量(最高畫質(zhì))
_qualityPreset = AVAssetExportPresetHighestQuality;
// 如果視頻大于 1000MB 則最低畫質(zhì)壓縮
if (videoSize > 1000) {
_qualityPreset = AVAssetExportPresetLowQuality;
} else if (videoSize > 20) {
// 中等畫質(zhì)壓縮
_qualityPreset = AVAssetExportPresetMediumQuality;
}
// 配置輸出的視頻文件,保存在app自己的沙盒路徑里,在上傳后刪除掉。
NSURL *newVideoUrl;
NSDateFormatter *formater = [[NSDateFormatter alloc] init];
//用時(shí)間給文件全名,以免重復(fù),在測(cè)試的時(shí)候其實(shí)可以判斷文件是否存在若存在,則刪除,重新生成文件即可
[formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;
[picker dismissViewControllerAnimated:YES completion:nil];
[self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
}
// 視頻壓縮轉(zhuǎn)碼處理
- (void)convertVideoQuailtyWithInputURL:(NSURL*)inputURL
outputURL:(NSURL*)outputURL
completeHandler:(void (^)(AVAssetExportSession*))handler {
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
if (!_qualityPreset) {
_qualityPreset = AVAssetExportPresetMediumQuality;
}
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:_qualityPreset];
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");
CGFloat videoSize = [self getFileSize:[outputURL path]];
NSLog(@"壓縮處理后的視頻時(shí)長(zhǎng):%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
NSLog(@"壓縮處理后的視頻大小:%@", [NSString stringWithFormat:@"%.2f MB", videoSize]);
// 導(dǎo)出完成后再賦值
_videoPath = [outputURL path];
break;
case AVAssetExportSessionStatusFailed:
NSLog(@"AVAssetExportSessionStatusFailed");
break;
}
}];
}
#pragma mark *** Video Handling -------------- End -------------- ***
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。