AVFoundation的一些方法

第一幀一直黑屏的原因:在寫的時(shí)候要判斷是視頻先宠能,然后開始寫入O骸1》纭牢贸!

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    if (!_recoding) return;
    @autoreleasepool {
        _currentSampleTime = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer);
        if (captureOutput == _videoDataOut && _assetWriter.status != AVAssetWriterStatusWriting && _assetWriter.status != AVAssetWriterStatusFailed) {
            [_assetWriter startWriting];
            [_assetWriter startSessionAtSourceTime:_currentSampleTime];
        }
        if (captureOutput == _videoDataOut) {
            if (_assetWriterPixelBufferInput.assetWriterInput.isReadyForMoreMediaData) {
                CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
                [self getStillImage:sampleBuffer];
                BOOL success = [_assetWriterPixelBufferInput appendPixelBuffer:pixelBuffer withPresentationTime:_currentSampleTime];
                if (!success) {
                    NSLog(@"Pixel Buffer沒有append成功");
                }
            }
        }
        if (captureOutput == _audioDataOut) {
            if(_assetWriter.status != AVAssetWriterStatusUnknown){
                [_assetWriterAudioInput appendSampleBuffer:sampleBuffer];
            }
        }
    }
}

視頻方向判斷

#pragma mark - 重力感應(yīng)相關(guān)
- (CMMotionManager *)motionManager {
    if (!_motionManager) {
        _motionManager = [[CMMotionManager alloc] init];
    }
    return _motionManager;
}
/**
 *  開始監(jiān)聽屏幕方向
 */
- (void)startUpdateAccelerometer {
    HCWS(ws);
    if ([self.motionManager isAccelerometerAvailable] == YES) {
        //回調(diào)會(huì)一直調(diào)用,建議獲取到就調(diào)用下面的停止方法竹观,需要再重新開始,當(dāng)然如果需求是實(shí)時(shí)不間斷的話可以等離開頁(yè)面之后再stop
        [self.motionManager setAccelerometerUpdateInterval:1.0];
        [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
             double x = accelerometerData.acceleration.x;
             double y = accelerometerData.acceleration.y;
             if (fabs(y) >= fabs(x)) {
                 if (y >= 0) {
                     DLog(@"----Down");
                     ws.shootingOrientation = UIDeviceOrientationPortraitUpsideDown;
                 }
                 else {
                     DLog(@"----Portrait");
                     ws.shootingOrientation = UIDeviceOrientationPortrait;
                 }
             }
             else {
                 if (x >= 0) {
                     DLog(@"----Right");
                     ws.shootingOrientation = UIDeviceOrientationLandscapeRight;
                 }
                 else {
                     DLog(@"----Left");
                     ws.shootingOrientation = UIDeviceOrientationLandscapeLeft;
                 }
             }
         }];
    }
}
/**
 *  停止監(jiān)聽屏幕方向
 */
- (void)stopUpdateAccelerometer {
    if ([self.motionManager isAccelerometerActive] == YES) {
        [self.motionManager stopAccelerometerUpdates];
        _motionManager = nil;
    }
}
- (void)canBtnActive {
    [self stopUpdateAccelerometer];
}
- (void)backVideoAction {
    [self startUpdateAccelerometer];
}

視頻旋轉(zhuǎn)

    if (self.shootingOrientation == UIDeviceOrientationLandscapeRight)
    {
        _assetWriterVideoInput.transform = _isAVCaptureDevicePositionFront ? CGAffineTransformMakeRotation(0) : CGAffineTransformMakeRotation(M_PI);
    }
    else if (self.shootingOrientation == UIDeviceOrientationLandscapeLeft)
    {
        _assetWriterVideoInput.transform = _isAVCaptureDevicePositionFront ? CGAffineTransformMakeRotation(M_PI) : CGAffineTransformMakeRotation(0);
    }
    else if (self.shootingOrientation == UIDeviceOrientationPortraitUpsideDown)
    {
        _assetWriterVideoInput.transform = _isAVCaptureDevicePositionFront ? CGAffineTransformMakeRotation(M_PI / 2.0) : CGAffineTransformMakeRotation(M_PI + (M_PI / 2.0));
    }
    else
    {
        _assetWriterVideoInput.transform = _isAVCaptureDevicePositionFront ? CGAffineTransformMakeRotation(M_PI + (M_PI / 2.0)) : CGAffineTransformMakeRotation(M_PI / 2.0);
    }

視頻鏡像

- (void)videoMirored {
    AVCaptureSession* session = (AVCaptureSession *)_videoSession;
    for (AVCaptureVideoDataOutput* output in session.outputs) {
        for (AVCaptureConnection * av in output.connections) {
            //判斷是否是前置攝像頭狀態(tài)
            if (_isAVCaptureDevicePositionFront) {
                if (av.supportsVideoMirroring) {
                    //鏡像設(shè)置
                    av.videoMirrored = YES;
                }
            }
        }
    }
}

縮略圖旋轉(zhuǎn)

+ (void)saveThumImageWithVideoURL:(NSURL *)videoUrl second:(int64_t)second orientation:(UIDeviceOrientation) shootingOrientation captureDevicePositionFront:(BOOL)isFront {
    AVURLAsset *urlSet = [AVURLAsset assetWithURL:videoUrl];
    AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlSet];
    
    CMTime time = CMTimeMake(second, 10);
    NSError *error = nil;
    CGImageRef cgimage = [imageGenerator copyCGImageAtTime:time actualTime:nil error:&error];
    if (error) {
        NSLog(@"縮略圖獲取失敗!:%@",error);
        return;
    }
    UIImage *image = [UIImage imageWithCGImage:cgimage];
    UIImage *finalImage = nil;
    if (shootingOrientation == UIDeviceOrientationLandscapeRight)
    {
        finalImage = [self rotateImage:image withOrientation:UIImageOrientationDown captureDevicePositionFront:isFront];
    }
    else if (shootingOrientation == UIDeviceOrientationLandscapeLeft)
    {
        finalImage = [self rotateImage:image withOrientation:UIImageOrientationUp captureDevicePositionFront:isFront];
    }
    else if (shootingOrientation == UIDeviceOrientationPortraitUpsideDown)
    {
        finalImage = [self rotateImage:image withOrientation:UIImageOrientationLeft captureDevicePositionFront:isFront];
    }
    else
    {
        finalImage = [self rotateImage:image withOrientation:UIImageOrientationRight captureDevicePositionFront:isFront];
    }
    NSData *imgData = UIImageJPEGRepresentation(finalImage, 1.0);
    NSString *videoPath = [videoUrl.absoluteString stringByReplacingOccurrencesOfString:@"file://" withString: @""];
    NSString *thumPath = [videoPath stringByReplacingOccurrencesOfString:@"mp4" withString: @"JPG"];
    BOOL isok = [imgData writeToFile:[SourceManage getFilePathName:[thumPath md5Hex] fileType:forFileImage] atomically: YES];
    NSLog(@"縮略圖獲取結(jié)果:%d",isok);
    
    CGImageRelease(cgimage);
}

+ (UIImage *)rotateImage:(UIImage *)image withOrientation:(UIImageOrientation)orientation captureDevicePositionFront:(BOOL)isFront
{
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    
    switch (orientation)
    {
        case UIImageOrientationLeft:
            rotate = M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = 0;
            translateY = -rect.size.width;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationRight:
            rotate = 3 * M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = -rect.size.height;
            translateY = 0;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationDown:
            if (isFront) {
                rotate = 0.0;
                rect = CGRectMake(0, 0, image.size.width, image.size.height);
                translateX = 0;
                translateY = 0;
            } else {
                rotate = M_PI;
                rect = CGRectMake(0, 0, image.size.width, image.size.height);
                translateX = -rect.size.width;
                translateY = -rect.size.height;
            }
            break;
        default:
            if (isFront) {
                rotate = M_PI;
                rect = CGRectMake(0, 0, image.size.width, image.size.height);
                translateX = -rect.size.width;
                translateY = -rect.size.height;
            } else {
                rotate = 0.0;
                rect = CGRectMake(0, 0, image.size.width, image.size.height);
                translateX = 0;
                translateY = 0;
            }
            break;
    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM變換
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //繪制圖片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    return newPic;
}

壓縮視頻長(zhǎng)度

+(void)CompressVideoUrlPath:(NSURL *)pathUrl startCompress:(StartCompress)start finishCompress:(FinishCompress)finish errorCompress:(errorCompress)err
{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:pathUrl options:nil];
    //獲取視頻總時(shí)長(zhǎng)
    float duration = CMTimeGetSeconds(avAsset.duration);
    float startTime = 0;
    float endTime = duration;
    
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    LYVideoCompress *comp = [[LYVideoCompress alloc] init];
    if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用時(shí)間給文件全名潜索,以免重復(fù)臭增,在測(cè)試的時(shí)候其實(shí)可以判斷文件是否存在若存在,則刪除竹习,重新生成文件即可
        [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
        comp.compressFilePath = [[self getFilePath] stringByAppendingFormat:@"%@.mp4", [formater stringFromDate:[NSDate date]]];
        exportSession.outputURL = [NSURL fileURLWithPath:comp.compressFilePath];
        exportSession.outputFileType = AVFileTypeMPEG4;
        exportSession.shouldOptimizeForNetworkUse = YES;
        
        CMTime start = CMTimeMakeWithSeconds(startTime, avAsset.duration.timescale);
        CMTime duration = CMTimeMakeWithSeconds(endTime - startTime,avAsset.duration.timescale);
        CMTimeRange range = CMTimeRangeMake(start, duration);
        exportSession.timeRange = range;
        
        [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
         {
             if (exportSession.status == AVAssetExportSessionStatusCompleted) {
                 comp.fileSize = [self getFileSize:comp.compressFilePath];
                 comp.fileLength = [self getVideoLength:comp.compressFilePath];
                 comp.thumAbsolutePath = [self savaThumeImagePath:comp.compressFilePath];
                 UIImage *image = [UIImage imageWithContentsOfFile:comp.thumAbsolutePath];
                 comp.height = [NSString stringWithFormat:@"%f", image.size.height];
                 comp.width = [NSString stringWithFormat:@"%f", image.size.width];
                 finish(comp);
             }else {
                 err(exportSession.error);
             }
         }];
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末誊抛,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子整陌,更是在濱河造成了極大的恐慌拗窃,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件泌辫,死亡現(xiàn)場(chǎng)離奇詭異随夸,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)震放,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門宾毒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人殿遂,你說(shuō)我怎么就攤上這事诈铛。” “怎么了墨礁?”我有些...
    開封第一講書人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵幢竹,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我恩静,道長(zhǎng)焕毫,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任蜕企,我火速辦了婚禮咬荷,結(jié)果婚禮上冠句,老公的妹妹穿的比我還像新娘轻掩。我一直安慰自己,他們只是感情好懦底,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開白布唇牧。 她就那樣靜靜地躺著罕扎,像睡著了一般。 火紅的嫁衣襯著肌膚如雪丐重。 梳的紋絲不亂的頭發(fā)上腔召,一...
    開封第一講書人閱讀 48,970評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音扮惦,去河邊找鬼臀蛛。 笑死,一個(gè)胖子當(dāng)著我的面吹牛崖蜜,可吹牛的內(nèi)容都是我干的浊仆。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼豫领,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼抡柿!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起等恐,我...
    開封第一講書人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤洲劣,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后课蔬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體囱稽,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年购笆,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了粗悯。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡同欠,死狀恐怖样傍,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情铺遂,我是刑警寧澤衫哥,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布,位于F島的核電站襟锐,受9級(jí)特大地震影響撤逢,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜粮坞,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一蚊荣、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧莫杈,春花似錦互例、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)腥光。三九已至,卻和暖如春糊秆,著一層夾襖步出監(jiān)牢的瞬間武福,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來(lái)泰國(guó)打工痘番, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留捉片,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓汞舱,卻偏偏與公主長(zhǎng)得像界睁,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子兵拢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容