将AVAsset读入帧并编译回视频

时间:2015-07-07 15:22:10

标签: ios objective-c avassetwriter avassetreader

大家好!我的项目中的想法是收集视频,将其拆分成帧,然后逐帧(而不是主题)应用特定效果,然后将所有内容编译回来。

使用以下代码,我可以将视频读入帧并将其传递到数组中:

//initialize avassetreader
AVAsset *avAsset = [AVAsset assetWithURL:url];
NSError *error = nil;
AVAssetReader *reader = [[AVAssetReader alloc] initWithAsset:avAsset error:&error];

//get video track
NSArray *videoTracks = [avAsset tracksWithMediaType:AVMediaTypeVideo];
AVAssetTrack *videoTrack = [videoTracks objectAtIndex:0];

NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];

AVAssetReaderTrackOutput *asset_reader_output = [[AVAssetReaderTrackOutput alloc] initWithTrack:videoTrack outputSettings:options];

[reader addOutput:asset_reader_output];
[reader startReading];

接下来,正如我上面所说,我逐帧阅读轨道

//while there is something to read
while ( [reader status]==AVAssetReaderStatusReading ) { 


    CMSampleBufferRef sampleBuffer = [asset_reader_output copyNextSampleBuffer];
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

    // Lock the base address of the pixel buffer
    CVPixelBufferLockBaseAddress(imageBuffer, 0);

    // Get the number of bytes per row for the pixel buffer
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);

    // Get the pixel buffer width and height
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);

    //Generate image to edit
    unsigned char* pixel = (unsigned char *)CVPixelBufferGetBaseAddress(imageBuffer);
    CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
    CGContextRef context=CGBitmapContextCreate(pixel, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little|kCGImageAlphaPremultipliedFirst);

    CGImageRef image = CGBitmapContextCreateImage(context);
    UIImage* myImage = [[UIImage alloc] initWithCGImage:image];
    [photos addObject:myImage];

}

我可以把所有东西放到一个数组中但是我需要将所有内容编译回视频轨道,用原始轨道的音频编译它然后保存。但是,我无法在网上找到任何有用的信息。请帮助!

提前致谢!

1 个答案:

答案 0 :(得分:2)

一旦你有一个图像数组,AVAssetWriter就是你的朋友。