02 将几张图片合成为一个视频

 将几张图片合成为一个视频,是我在网址找到的方法做成了一个Demo,分享给大家

一、代码

    // 初始化压缩引擎
    AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:self.moviePath] fileType:AVFileTypeQuickTimeMovie error:&error];
    // 设置生成的视频的参数,尺寸和编码格式
    NSDictionary *videoSetting = [NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecH264,AVVideoCodecKey,[NSNumber numberWithInt:movieSize.width],AVVideoWidthKey,[NSNumber numberWithInt:movieSize.height],AVVideoHeightKey, nil];
    // 将多张图片合成为一个视频文件的主体代码
    dispatch_queue_t queue = dispatch_queue_create("mediaInputQueue", NULL);
    int __block frame = 0;

    [writerInput requestMediaDataWhenReadyOnQueue:queue usingBlock:^{
        
        while ([writerInput isReadyForMoreMediaData]) {
            if(++frame >= [self.imageArr count] * 10){
                [writerInput markAsFinished];
                [videoWriter finishWritingWithCompletionHandler:^{
                    
                    NSLog(@"结束了");
                    
                }];
                break;
            }
            
            CVPixelBufferRef buffer = NULL;
            // 和下面的CMTimeMake(frame, 5)一起控制视频的长度,和上面的 [self.imageArr count] * 10 中的10 是一个
            int idx = frame / 10;
            
            NSLog(@"idx == %d",idx);
            
            buffer = [self pixelBufferFromCGImage:[[self.imageArr objectAtIndex:idx] CGImage] size:movieSize];
            
            if(buffer){
                // 将获得的视频段添加到一起
                if([adaptor appendPixelBuffer:buffer withPresentationTime:CMTimeMake(frame, 5)]){
                    NSLog(@"写入成功");
                }
                else{
                    NSLog(@"写入失败");
                    CFRelease(buffer);
                }
            }
        }
    }];
    // 把CGImageRef格式转换为CVPixelBufferRef格式
- (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image size:(CGSize)size

二、工程地址

工程地址



你可能感兴趣的:(iOS,第二个项目)