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);
             }
         }];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,482评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,377评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,762评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,273评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,289评论 5 373
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,046评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,351评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,988评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,476评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,948评论 2 324
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,064评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,712评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,261评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,264评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,486评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,511评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,802评论 2 345

推荐阅读更多精彩内容