话不多说 ,直接上码,(无优化,只是实现了功能,测试播放起来飞快)
- (void)doit:(NSURL *)moviePath{
static CALayer *layer=nil;
if(!layer){
layer=[CALayer layer];
layer.frame=CGRectMake(20, 0, 320, 320);
layer.contentsGravity=kCAGravityBottomLeft;
layer.contentsScale=[UIScreen mainScreen].scale;
[self.view.layer addSublayer:layer];
[CATransaction setDisableActions:YES];
}
AVURLAsset *set=[AVURLAsset URLAssetWithURL:moviePath options:nil];
NSError *error;
AVAssetReader *asset_reader = [[AVAssetReader alloc]initWithAsset:set error:&error];
AVAssetTrack* video_track=[[set tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
[dictionary setObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(NSString *)kCVPixelBufferPixelFormatTypeKey];
AVAssetReaderTrackOutput *asset_reader_output=[[AVAssetReaderTrackOutput alloc]initWithTrack:video_track outputSettings:dictionary];
if([asset_reader canAddOutput:asset_reader_output]){
[asset_reader addOutput:asset_reader_output];
}
if([asset_reader startReading]){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
CMSampleBufferRef buffer=NULL;
while ([asset_reader status]==AVAssetReaderStatusReading) {
buffer=[asset_reader_output copyNextSampleBuffer];
if(buffer){
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(buffer);
CVPixelBufferLockBaseAddress(imageBuffer,0);
uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef newContext = CGBitmapContextCreate(baseAddress,
width, height,
8,
bytesPerRow,
colorSpace,
kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGImageRef newImage = CGBitmapContextCreateImage(newContext);
CGContextRelease(newContext);
CGColorSpaceRelease(colorSpace);
[layer performSelectorOnMainThread:@selector(setContents:) withObject:(id)newImage waitUntilDone:YES];
CFRelease(newImage);
CFRelease(buffer);
}
}
});
}
}