AVFoundation的一些方法

第一幀一直黑屏的原因:在寫的時(shí)候要判斷是視頻先,然后開始寫入?。?!

- (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í)不間斷的話可以等離開頁面之后再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;
}

壓縮視頻長度

+(void)CompressVideoUrlPath:(NSURL *)pathUrl startCompress:(StartCompress)start finishCompress:(FinishCompress)finish errorCompress:(errorCompress)err
{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:pathUrl options:nil];
    //獲取視頻總時(shí)長
    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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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