AVFoundation的一些方法

第一帧一直黑屏的原因:在写的时候要判断是视频先,然后开始写入!!!

- (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 - 重力感应相关
- (CMMotionManager *)motionManager {
    if (!_motionManager) {
        _motionManager = [[CMMotionManager alloc] init];
    }
    return _motionManager;
}
/**
 *  开始监听屏幕方向
 */
- (void)startUpdateAccelerometer {
    HCWS(ws);
    if ([self.motionManager isAccelerometerAvailable] == YES) {
        //回调会一直调用,建议获取到就调用下面的停止方法,需要再重新开始,当然如果需求是实时不间断的话可以等离开页面之后再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;
                 }
             }
         }];
    }
}
/**
 *  停止监听屏幕方向
 */
- (void)stopUpdateAccelerometer {
    if ([self.motionManager isAccelerometerActive] == YES) {
        [self.motionManager stopAccelerometerUpdates];
        _motionManager = nil;
    }
}
- (void)canBtnActive {
    [self stopUpdateAccelerometer];
}
- (void)backVideoAction {
    [self startUpdateAccelerometer];
}

视频旋转

    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) {
            //判断是否是前置摄像头状态
            if (_isAVCaptureDevicePositionFront) {
                if (av.supportsVideoMirroring) {
                    //镜像设置
                    av.videoMirrored = YES;
                }
            }
        }
    }
}

缩略图旋转

+ (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(@"缩略图获取结果:%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];
    //获取视频总时长
    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];//用时间给文件全名,以免重复,在测试的时候其实可以判断文件是否存在若存在,则删除,重新生成文件即可
        [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);
             }
         }];
    }
}

你可能感兴趣的:(AVFoundation的一些方法)