iOS開發(fā) - 系統(tǒng)原生視頻壓縮處理方式

需要導(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ù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,153評(píng)論 25 708
  • 說不出口的難過,在一刻間淚涌,我不知道現(xiàn)在的我能干什么,常常懷疑著自己,從前的細(xì)心好像也慌了神,時(shí)而在,時(shí)而不在。...
    琪梔夢(mèng)閱讀 474評(píng)論 3 2
  • 我們今天繼續(xù)的進(jìn)行了光學(xué)系統(tǒng)的設(shè)計(jì)練習(xí)。今天把昨天畫的鏡子模型都重新的修改了一遍,然后在裝配 圖里用約束都裝配完...
    高俊01閱讀 171評(píng)論 0 0
  • 從現(xiàn)在開始,要求你和其他人都一樣,他們做什么,你跟著做什么,當(dāng)然,你也不能有其它額外的想法,你的想法一直是想著和別...
    白樺i閱讀 316評(píng)論 0 0
  • 一、朋友的分享 前幾篇文章我倡議,大家把做實(shí)驗(yàn)的圖片或者視頻都分享出來,還真有朋友發(fā)給我。今天先分享李大明朋友的圖...
    王顥閱讀 2,109評(píng)論 0 1

友情鏈接更多精彩內(nèi)容