Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -(void) writeImagesToMovieAtPath:(NSString *) path withSize:(CGSize) size
- {
- if ([[NSFileManager defaultManager] fileExistsAtPath:path])
- {
- [[NSFileManager defaultManager]removeItemAtPath:path error:nil];
- }
- NSLog(@"Started");
- NSError *error = nil;
- AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:
- [NSURL fileURLWithPath:path] fileType:AVFileTypeMPEG4
- error:&error];
- NSParameterAssert(videoWriter);
- NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
- AVVideoCodecH264, AVVideoCodecKey,
- [NSNumber numberWithInt:size.width], AVVideoWidthKey,
- [NSNumber numberWithInt:size.height], AVVideoHeightKey,
- nil];
- AVAssetWriterInput* videoWriterInput = [AVAssetWriterInput
- assetWriterInputWithMediaType:AVMediaTypeVideo
- outputSettings:videoSettings] ;
- AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor
- assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput
- sourcePixelBufferAttributes:nil];
- NSParameterAssert(videoWriterInput);
- NSParameterAssert([videoWriter canAddInput:videoWriterInput]);
- videoWriterInput.expectsMediaDataInRealTime = YES;
- [videoWriter addInput:videoWriterInput];
- //Start a session:
- [videoWriter startWriting];
- [videoWriter startSessionAtSourceTime:kCMTimeZero];
- //Video encoding
- CVPixelBufferRef buffer = NULL;
- //convert uiimage to CGImage.
- int frameCount = 0;
- for(int i = 0; i<[imageArray count]; i++)
- {
- buffer = [self pixelBufferFromCGImage:[[imageArray objectAtIndex:i] CGImage] ];
- BOOL append_ok = NO;
- int j = 0;
- while (!append_ok && j< 30)
- {
- if (adaptor.assetWriterInput.readyForMoreMediaData)
- {
- printf("appending %d attemp %d\n", frameCount, j);
- CMTime frameTime = CMTimeMake(frameCount,(int32_t) 10);
- append_ok = [adaptor appendPixelBuffer:buffer withPresentationTime:frameTime];
- /* CVPixelBufferPoolRef bufferPool = adaptor.pixelBufferPool;
- NSParameterAssert(bufferPool != NULL);*/
- [NSThread sleepForTimeInterval:0.05];
- }
- else
- {
- printf("adaptor not ready %d, %d\n", frameCount, j);
- [NSThread sleepForTimeInterval:0.1];
- }
- j++;
- }
- if (!append_ok)
- {
- printf("error appending image %d times %d\n", frameCount, j);
- }
- frameCount++;
- CVBufferRelease(buffer);
- }
- [videoWriterInput markAsFinished];
- [videoWriter finishWriting];
- // [m_PictArray removeAllObjects];
- NSLog(@"Write Ended");
- [self CompileFilesToMakeMovie];
- }
- - (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image
- {
- NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
- [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
- [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
- nil];
- CVPixelBufferRef pxbuffer = NULL;
- CVPixelBufferCreate(kCFAllocatorDefault, CGImageGetWidth(image),
- CGImageGetHeight(image), kCVPixelFormatType_32ARGB, (__bridge CFDictionaryRef) options,
- &pxbuffer);
- CVPixelBufferLockBaseAddress(pxbuffer, 0);
- void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
- CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
- CGContextRef context = CGBitmapContextCreate(pxdata, CGImageGetWidth(image),
- CGImageGetHeight(image), 8, 4*CGImageGetWidth(image), rgbColorSpace,
- kCGImageAlphaNoneSkipFirst);
- CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
- CGAffineTransform flipVertical = CGAffineTransformMake(
- 1, 0, 0, -1, 0, CGImageGetHeight(image)
- );
- CGContextConcatCTM(context, flipVertical);
- CGAffineTransform flipHorizontal = CGAffineTransformMake(
- -1.0, 0.0, 0.0, 1.0, CGImageGetWidth(image), 0.0
- );
- CGContextConcatCTM(context, flipHorizontal);
- CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
- CGImageGetHeight(image)), image);
- CGColorSpaceRelease(rgbColorSpace);
- CGContextRelease(context);
- CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
- return pxbuffer;
- }
- //WRITE AUDIO TO MOVIE CONTAINING IMAGE ARRAY
- -(void)CompileFilesToMakeMovie
- {
- AVMutableComposition* mixComposition = [AVMutableComposition composition];
- NSString* audio_inputFileName = @"audio.caf";
- NSString* audio_inputFilePath = [NSString stringWithFormat:@"%@/%@", DOCUMENTS_FOLDER,audio_inputFileName];
- NSURL* audio_inputFileUrl = [NSURL fileURLWithPath:audio_inputFilePath];
- NSString* video_inputFileName = @"video1.mov";
- NSString* video_inputFilePath = [NSString stringWithFormat:@"%@/%@", DOCUMENTS_FOLDER,video_inputFileName];
- NSURL* video_inputFileUrl = [NSURL fileURLWithPath:video_inputFilePath];
- NSString* outputFileName = @"outputFile.mov";
- NSString* outputFilePath = [NSString stringWithFormat:@"%@/%@", DOCUMENTS_FOLDER,outputFileName];
- NSURL* outputFileUrl = [NSURL fileURLWithPath:outputFilePath];
- if ([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath])
- [[NSFileManager defaultManager] removeItemAtPath:outputFilePath error:nil];
- CMTime nextClipStartTime = kCMTimeZero;
- AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:video_inputFileUrl options:nil];
- CMTimeRange video_timeRange = CMTimeRangeMake(kCMTimeZero,videoAsset.duration);
- AVMutableCompositionTrack *a_compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
- [a_compositionVideoTrack insertTimeRange:video_timeRange ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:nextClipStartTime error:nil];
- //nextClipStartTime = CMTimeAdd(nextClipStartTime, a_timeRange.duration);
- AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audio_inputFileUrl options:nil];
- CMTimeRange audio_timeRange = CMTimeRangeMake(kCMTimeZero, audioAsset.duration);
- AVMutableCompositionTrack *b_compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
- [b_compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:nextClipStartTime error:nil];
- AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
- _assetExport.outputFileType = @"com.apple.quicktime-movie";
- _assetExport.outputURL = outputFileUrl;
- [_assetExport exportAsynchronouslyWithCompletionHandler:
- ^(void ) {
- [self saveVideoToAlbum:outputFilePath];
- }
- ];
- }
- - (void) saveVideoToAlbum:(NSString *)path{
- NSLog(@"Saved video to the Album!");
- // Alerting the user of a successful saving and popping to the main view
- UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:@"Success!"
- message:@"Your video has been saved to your device's photo album!"
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [successAlert show];
- if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path)){
- UISaveVideoAtPathToSavedPhotosAlbum (path, self, @selector(video:didFinishSavingWithError: contextInfo:), nil);
- }
- }
- - (void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo {
- NSLog(@"Finished saving video with error: %@", error);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement