ios 将音频和图片合成为视频

.h

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <UIKit/UIKit.h>

typedef void(^VideoBuildCompletion) (NSString *videoPath);

@interface VideoBuilder : NSObject

- (void)makeVideoWithImage:(UIImage *)image
                     audio:(NSString *)audioFile
                completion:(VideoBuildCompletion)completion;

@end

.m

#import "VideoBuilder.h"
#import "STLSFileManager.h"

typedef void(^successBlock)(void);
typedef void(^failBlock)(NSError *error);
typedef void(^exportAsynchronouslyWithCompletionHandler)(void);
typedef void(^convertToMp4Completed)(void);

@interface VideoBuilder ()

@property (nonatomic, strong) AVAssetWriter *videoWriter;
@property (nonatomic, strong) AVAssetWriterInputPixelBufferAdaptor *adaptor;
@property (nonatomic, strong) AVAssetWriterInput *writerInput;

@property (nonatomic, assign) NSInteger frameNumber;

@property (nonatomic, assign) CGSize    videoSize;
@property (nonatomic, strong) NSString *videoPath;
@property (nonatomic, assign) int32_t timeScale;
@property (nonatomic, strong) NSString *audioFile;
@end

@implementation VideoBuilder

- (void)maskFinishWithSuccess:(successBlock)success Fail:(failBlock)fail {
    
    [self.writerInput markAsFinished];
    
    [self.videoWriter finishWritingWithCompletionHandler:^{
        if (self.videoWriter.status != AVAssetReaderStatusFailed && self.videoWriter.status == AVAssetWriterStatusCompleted) {
            
            if (success) {
                success();
            }
            
        } else {
            if (fail) {
                fail(_videoWriter.error);
            }
            
            NSLog(@"create video failed, %@",self.videoWriter.error);
        }
    }];
    
    CVPixelBufferPoolRelease(self.adaptor.pixelBufferPool);
}

//初始化写入流 AVAssetWriter
- (void)initWriter{
    
    NSString *videoOutputPath = [[[STLSFileManager sharedFileManager] tempVideoFilesFolder] stringByAppendingString:[NSString stringWithFormat:@"/%@.output.mov",[[self.audioFile stringByDeletingPathExtension] lastPathComponent]]];
    
    _videoSize = CGSizeMake(160, 90);
    _videoPath = videoOutputPath;
    _timeScale = 1;
    
    NSError *fileError;
    if ([[NSFileManager defaultManager] removeItemAtPath:self.videoPath error:&fileError]) {
    }
    NSError *error = nil;
    //告诉AVAssetWriter 文件保存路径、文件type
    self.videoWriter = [[AVAssetWriter alloc]initWithURL:[NSURL fileURLWithPath:_videoPath]
                                                fileType:AVFileTypeQuickTimeMovie
                                                   error:&error];
    
    NSParameterAssert(self.videoWriter);
    //视频的基本设置,编码格式、宽、高
    NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                   AVVideoCodecH264,AVVideoCodecKey,
                                   [NSNumber numberWithInt:_videoSize.width],AVVideoWidthKey,
                                   [NSNumber numberWithInt:_videoSize.height],AVVideoHeightKey,
                                   nil];
    //根据定义好的视频格式定义输入流
    self.writerInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo
                                                          outputSettings:videoSettings];
    // expectsMediaDataInRealTime设置为YES, 表示实时获取摄像头和麦克风采集到的视频数据和音频数据
    self.writerInput.expectsMediaDataInRealTime = YES;
    //AVAssetWriterInputPixelBufferAdaptor负责将图片转成的缓存数据CVPixelBufferRef追加到AVAssetWriterInput中。
    self.adaptor = [AVAssetWriterInputPixelBufferAdaptor
                    assetWriterInputPixelBufferAdaptorWithAssetWriterInput:self.writerInput
                    sourcePixelBufferAttributes:nil];
    
    NSParameterAssert(self.writerInput);
    NSParameterAssert([self.videoWriter canAddInput:self.writerInput]);
    
    [self.videoWriter addInput:self.writerInput];
    
    [self.videoWriter startWriting];
    
    [self.videoWriter startSessionAtSourceTime:kCMTimeZero];
}

//将图片合成为视频
- (void)convertVideoWithImageArray:(NSArray *)images Success:(successBlock)success Fail:(failBlock)fail {
    
    [self initWriter];
    // GCD 异步
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        //获取音频的时长
        AVURLAsset* audioAsse = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:self.audioFile] options:nil];
        CMTime cmtime = audioAsse.duration;
        NSUInteger dTotalSeconds = CMTimeGetSeconds(cmtime);
        
        double numberOfSecondsPerFrame = dTotalSeconds/[images count];
        if (numberOfSecondsPerFrame == 0) {
            numberOfSecondsPerFrame = 1;
        }
        double frameDuration = self.timeScale * numberOfSecondsPerFrame;

        int i;
        CVPixelBufferRef buffer = NULL;
        for ( i = 0; i < [images count];) {
            if (self.writerInput.readyForMoreMediaData) {
                //CMTimeMake(a,b) a当前第几帧, b每秒钟多少帧.当前播放时间a/b
                CMTime frameTime = CMTimeMake(1,self.timeScale);
                
                CMTime lastTime = CMTimeMake(i*frameDuration,self.timeScale);
                
                CMTime presentTime = CMTimeAdd(lastTime, frameTime);
                
                if (i == 0) {
                    presentTime = CMTimeMake(0,self.timeScale);
                }
                
                buffer = [self pixelBufferFromCGImage:[images[i] CGImage]];
                
                if (buffer) {
                    //添加视频流
                    if ([self.adaptor appendPixelBuffer:buffer withPresentationTime:lastTime]) {
                        i++;
                    }else{
                        [self maskFinishWithSuccess:success Fail:fail];
                        break;
                    }
                    
                    CVPixelBufferRelease(buffer);
                }
            }
        }
        
        if (i == images.count) {
            [self maskFinishWithSuccess:success Fail:fail];
        }
    });
}

// 将声音添加到视频里面
- (void)addAudioToVideoAudioPath:(NSString *)audioPath Completion:(exportAsynchronouslyWithCompletionHandler)completion {
    //初始化audioAsset
    AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:audioPath] options:nil];
    //初始化videoAsset
    AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:self.videoPath] options:nil];
    //初始化合成类
    AVMutableComposition* mixComposition = [AVMutableComposition composition];
    //初始化设置轨道type为AVMediaTypeAudio
    AVMutableCompositionTrack *compositionCommentaryTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    //根据音频时常添加到设置里面
    [compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];
    //初始化设置轨道type为VideoTrack
    AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    //设置视频时长等
    [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:kCMTimeZero error:nil];
    //初始化导出类
    AVAssetExportSession* assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetPassthrough];
    //导出路径
    NSString *exportPath = self.videoPath;
    NSURL *exportUrl = [NSURL fileURLWithPath:exportPath];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath])
    {
        [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
    }
    
    assetExport.outputFileType = AVFileTypeQuickTimeMovie;
    assetExport.outputURL = exportUrl;
    assetExport.shouldOptimizeForNetworkUse = YES;
    //导出
    [assetExport exportAsynchronouslyWithCompletionHandler:completion];
}

- (void)convertToMP4Completed:(convertToMp4Completed)Completed
{
    NSString *filePath = self.videoPath;
    NSString *mp4FilePath = [filePath stringByReplacingOccurrencesOfString:@"mov" withString:@"mp4"];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(queue, ^{
        
        AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:filePath] options:nil];
        NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
        if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
            AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetHighestQuality];
            exportSession.outputURL = [NSURL fileURLWithPath:mp4FilePath];
            exportSession.outputFileType = AVFileTypeMPEG4;
            if ([[NSFileManager defaultManager] fileExistsAtPath:mp4FilePath])
            {
                [[NSFileManager defaultManager] removeItemAtPath:mp4FilePath error:nil];
            }
            [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
             {
                 switch (exportSession.status) {
                     case AVAssetExportSessionStatusUnknown: {
                         NSLog(@"AVAssetExportSessionStatusUnknown");
                         break;
                     }
                     case AVAssetExportSessionStatusWaiting: {
                         NSLog(@"AVAssetExportSessionStatusWaiting");
                         break;
                     }
                     case AVAssetExportSessionStatusExporting: {
                         NSLog(@"AVAssetExportSessionStatusExporting");
                         break;
                     }
                     case AVAssetExportSessionStatusFailed: {
                         NSLog(@"AVAssetExportSessionStatusFailed error:%@", exportSession.error);
                         break;
                     }
                     case AVAssetExportSessionStatusCompleted: {
                         NSLog(@"AVAssetExportSessionStatusCompleted");
                         dispatch_async(dispatch_get_main_queue(),^{
                             Completed();
                         });
                         break;
                     }
                     default: {
                         NSLog(@"AVAssetExportSessionStatusCancelled");
                         break;
                     }
                 }
             }];
        }
    });
}


- (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image {
    CGFloat w = CGImageGetWidth(image);
    CGFloat h = CGImageGetHeight(image);
    NSLog(@"%f,%f",w,h);
    if (w >= h) {
        
    } else {
        CGFloat t = w;
        w = h;
        h = t;
    }
    if (image) {
        CGSize size = CGSizeMake(400, 320);
        
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
                                 [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
                                 nil];
        CVPixelBufferRef pxbuffer = NULL;
        
        CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault,
                                              size.width,
                                              size.height,
                                              kCVPixelFormatType_32ARGB,
                                              (__bridge CFDictionaryRef) options,
                                              &pxbuffer);
        if (status != kCVReturnSuccess){
            NSLog(@"Failed to create pixel buffer");
        }
        
        CVPixelBufferLockBaseAddress(pxbuffer, 0);
        void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
        
        CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(pxdata, size.width,
                                                     size.height, 8, 4*size.width, rgbColorSpace,
                                                     kCGImageAlphaPremultipliedFirst);
        //kCGImageAlphaNoneSkipFirst);
        CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
        CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
                                               CGImageGetHeight(image)), image);
        CGColorSpaceRelease(rgbColorSpace);
        CGContextRelease(context);
        
        CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
        
        return pxbuffer;
    } else {
        return NULL;
    }
}

- (void)makeVideoWithImage:(UIImage *)image
                     audio:(NSString *)audioFile
                completion:(VideoBuildCompletion)completion{
    //获取音频的本地路径
    self.audioFile = audioFile;
    __weak __typeof(self) weakSelf = self;
    [self convertVideoWithImageArray:@[image,image,image,image,image,image] Success:^{
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        __weak __typeof(strongSelf) weakweakSelf = strongSelf;
        [strongSelf addAudioToVideoAudioPath:audioFile Completion:^{
            __strong __typeof(weakweakSelf) strongstrongSelf = weakweakSelf;
            [strongstrongSelf convertToMP4Completed:^{
                if (completion) {
                    completion(strongstrongSelf.videoPath);
                }
            }];
        }];
    } Fail:^(NSError *error) {
    }];
}

@end

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容