iOS屏幕錄制步驟一:截屏、將截屏圖片合成視頻

寫在前面

公司近期讓做一個錄制屏幕類的App,我研究了iOS9新增的Replaykit框架,使用起來確實挺簡單的,性能也很好,但是獲取不到視頻文件,這一點就決定了我不能使用這個框架。那么我只能使用最原始的方法,抓取view的截圖,然后將這些截圖合成視頻,最后再把同時錄制的音頻合成到視頻中。這篇文章先介紹如何抓取截圖并合成視頻。

抓取截屏

先貼一下代碼:通過一個layer抓取屏幕截圖

/// view => screen shot image
- (UIImage *)fetchScreenshot {
    UIImage *image = nil;
    if (self.captureLayer) {
        CGSize imageSize = self.captureLayer.bounds.size;
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [self.captureLayer renderInContext:context];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    return image;
}

上面的方法主要通過使用圖形上下文CGContextRef來抓取layer的內容。代碼很簡單,不做過多的解釋了。

將CGImage轉換成CVPixelBufferRef緩存數據

/// image => PixelBuffer
- (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image {
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
                             nil];
    
    CVPixelBufferRef pxbuffer = NULL;
    
    CGFloat frameWidth = CGImageGetWidth(image);
    CGFloat frameHeight = CGImageGetHeight(image);
    
    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault,frameWidth,frameHeight,kCVPixelFormatType_32ARGB,(__bridge CFDictionaryRef) options, &pxbuffer);
    
    NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);
    
    CVPixelBufferLockBaseAddress(pxbuffer, 0);
    void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
    NSParameterAssert(pxdata != NULL);
    
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pxdata, frameWidth, frameHeight, 8,CVPixelBufferGetBytesPerRow(pxbuffer),rgbColorSpace,(CGBitmapInfo)kCGImageAlphaNoneSkipFirst);
    
    NSParameterAssert(context);
    CGContextConcatCTM(context, CGAffineTransformIdentity);
    CGContextDrawImage(context, CGRectMake(0, 0,frameWidth,frameHeight),  image);
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);
    
    CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
    
    return pxbuffer;
}

只有將CGImage轉換成CVPixelBufferRef緩存數據后,才能存儲到視頻中。

將多張圖片合成視頻

將圖片合成視頻需要使用到以下幾個類:

AVAssetWriter

AVAssetWriter負責將媒體數據寫入到文件。創建AVAssetWriter對象需要傳入的參數包括文件的輸出路徑URL和文件格式。文件格式選擇AVFileTypeMPEG4即是MP4格式。

NSURL *fileUrl = [NSURL fileURLWithPath:self.videoPath];
    self.videoWriter = [[AVAssetWriter alloc] initWithURL:fileUrl fileType:AVFileTypeMPEG4 error:&error];
AVAssetWriterInput

AVAssetWriterInput負責存儲視頻或者音頻緩存數據,AVAssetWriterInput對象創建完成后需要添加到AVAssetWriter中。

// 設置視頻的編碼和尺寸
NSDictionary *videoCompressionProps = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithDouble:size.width * size.height], AVVideoAverageBitRateKey, nil];
    
    NSDictionary *videoSettings = @{AVVideoCodecKey: AVVideoCodecH264,
                                    AVVideoWidthKey: @(size.width),
                                    AVVideoHeightKey: @(size.height),
                                    AVVideoCompressionPropertiesKey: videoCompressionProps};
    
    self.videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
    
    NSParameterAssert(self.videoWriterInput);

    // expectsMediaDataInRealTime設置為YES, 表示實時獲取攝像頭和麥克風采集到的視頻數據和音頻數據
    self.videoWriterInput.expectsMediaDataInRealTime = YES;
AVAssetWriterInputPixelBufferAdaptor

AVAssetWriterInputPixelBufferAdaptor負責將圖片轉成的緩存數據CVPixelBufferRef追加到AVAssetWriterInput中。

NSDictionary *bufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, nil];
    
    self.adaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:self.videoWriterInput sourcePixelBufferAttributes:bufferAttributes];

以上只寫了圖片合成視頻的主要幾個點,如果大家有不明白的,或者需要參考代碼的話,請點擊以下鏈接:GitHub

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,813評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,180評論 4 61
  • 一不小心半年就要過完了,年初雄心壯志定下的那些計劃執行得如何呢? 春夏秋冬四季變換,春有百花秋有月到處浪,光忙著換...
    夜闌猶未寢閱讀 2,654評論 8 89
  • 昨個風風火回學校,其實我挺你不愿意來的。但是我用一句“年輕時不努力,什么時候努力。”把自己唬過來。其實我的三...
    李紫林閱讀 499評論 0 0
  • 我偶爾瞥視窗外 有綠的葉、紅的花、雜亂的草 還有顏色近乎曖昧的落葉與泥土 我偶爾瞥見窗外 有灰的路、飛滾的車輪、騰...
    又兔閱讀 553評論 4 8