iOS 視頻合成 (圖片和視頻的合成 ,視頻跟音頻的合成)

這個(gè) 給我的感覺(jué)就像是 PPT 播放一樣。這里找了一些資料,學(xué)習(xí)視頻合成方面的知識(shí)。

一:圖片和視頻的合成:


@interface ViewController ()

@property(nonatomic, strong)NSMutableArray *imageArr;

@property(nonatomic, strong)NSString? *theVideoPath;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

self.imageArr =[[NSMutableArray alloc]initWithObjects:

[UIImage imageNamed:@"1.jpg"],[UIImage imageNamed:@"2.jpg"],[UIImage imageNamed:@"3.jpg"],[UIImage imageNamed:@"4.jpg"],[UIImage imageNamed:@"5.jpg"],[UIImage imageNamed:@"6.jpg"],[UIImage imageNamed:@"7"],[UIImage imageNamed:@"8"],[UIImage imageNamed:@"9.jpg"],[UIImage imageNamed:@"10.jpg"],[UIImage imageNamed:@"11.jpg"],[UIImage imageNamed:@"12.jpg"],[UIImage imageNamed:@"13.jpg"],[UIImage imageNamed:@"14.jpg"],[UIImage imageNamed:@"15.jpg"],[UIImage imageNamed:@"16.jpg"],[UIImage imageNamed:@"17.jpg"],[UIImage imageNamed:@"18.jpg"],[UIImage imageNamed:@"19.jpg"],[UIImage imageNamed:@"20.jpg"],[UIImage imageNamed:@"21.jpg"],[UIImage imageNamed:@"22.jpg"],[UIImage imageNamed:@"23.jpg"],nil];

UIButton * button =[UIButton buttonWithType:UIButtonTypeRoundedRect];

[button setFrame:CGRectMake(100,100, 100,100)];

[button setTitle:@"合成"forState:UIControlStateNormal];

[button addTarget:self action:@selector(testCompressionSession)forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:button];

UIButton * button1 =[UIButton buttonWithType:UIButtonTypeRoundedRect];

[button1 setFrame:CGRectMake(100,200, 100,100)];

[button1 setTitle:@"播放"forState:UIControlStateNormal];

[button1 addTarget:self action:@selector(playAction)forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:button1];

// Do any additional setup after loading the view, typically from a nib.

}

-(void)testCompressionSession

{

NSLog(@"開始");

//NSString *moviePath = [[NSBundle mainBundle]pathForResource:@"Movie" ofType:@"mov"];

NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString *moviePath =[[paths objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",@"2016全球三大超跑宣傳片_超清"]];

self.theVideoPath=moviePath;

CGSize size =CGSizeMake(320,400);//定義視頻的大小

//[self writeImages:_imageArr ToMovieAtPath:moviePath withSize:size? inDuration:4 byFPS:30];//第2中方法

NSError *error =nil;

unlink([moviePath UTF8String]);

NSLog(@"path->%@",moviePath);

//—-initialize compression engine

AVAssetWriter *videoWriter =[[AVAssetWriter alloc]initWithURL:[NSURL fileURLWithPath:moviePath]fileType:AVFileTypeQuickTimeMovie?error:&error];

NSParameterAssert(videoWriter);

if(error)

NSLog(@"error =%@", [error localizedDescription]);

NSDictionary *videoSettings =[NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecH264,AVVideoCodecKey,

[NSNumber numberWithInt:size.width],AVVideoWidthKey,

[NSNumber numberWithInt:size.height],AVVideoHeightKey,nil];

AVAssetWriterInput *writerInput =[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];

NSDictionary*sourcePixelBufferAttributesDictionary =[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:kCVPixelFormatType_32ARGB],kCVPixelBufferPixelFormatTypeKey,nil];

AVAssetWriterInputPixelBufferAdaptor *adaptor =[AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput

sourcePixelBufferAttributes:sourcePixelBufferAttributesDictionary];

NSParameterAssert(writerInput);

NSParameterAssert([videoWriter canAddInput:writerInput]);

if ([videoWriter canAddInput:writerInput])

NSLog(@"11111");

else

NSLog(@"22222");

[videoWriter addInput:writerInput];

[videoWriter startWriting];

[videoWriter startSessionAtSourceTime:kCMTimeZero];

//合成多張圖片為一個(gè)視頻文件

dispatch_queue_t dispatchQueue =dispatch_queue_create("mediaInputQueue",NULL);

int __block frame =0;

[writerInput requestMediaDataWhenReadyOnQueue:dispatchQueue usingBlock:^{

while([writerInput isReadyForMoreMediaData])

{

if(++frame >=[self.imageArr count]*10)

{

[writerInput markAsFinished];

[videoWriter finishWriting];

break;}

CVPixelBufferRef buffer =NULL;

int idx =frame/10;

NSLog(@"idx==%d",idx);

buffer =(CVPixelBufferRef)

[self pixelBufferFromCGImage:[[self.imageArr objectAtIndex:idx]CGImage]size:size];

if (buffer){

if(![adaptor appendPixelBuffer:buffer withPresentationTime:CMTimeMake(frame,10)])

NSLog(@"FAIL");

else

NSLog(@"OK");

CFRelease(buffer);}}}];}

- (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image size:(CGSize)size{

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);

NSParameterAssert(status ==kCVReturnSuccess && pxbuffer !=NULL);

CVPixelBufferLockBaseAddress(pxbuffer,0);

void *pxdata =CVPixelBufferGetBaseAddress(pxbuffer);

NSParameterAssert(pxdata !=NULL);

CGColorSpaceRef rgbColorSpace=CGColorSpaceCreateDeviceRGB();

CGContextRef context =CGBitmapContextCreate(pxdata,size.width,size.height,8,4*size.width,rgbColorSpace,kCGImageAlphaPremultipliedFirst);

NSParameterAssert(context);

CGContextDrawImage(context,CGRectMake(0,0,CGImageGetWidth(image),CGImageGetHeight(image)), image);

CGColorSpaceRelease(rgbColorSpace);

CGContextRelease(context);

CVPixelBufferUnlockBaseAddress(pxbuffer,0);

return pxbuffer;}

-(void)playAction{

MPMoviePlayerViewController *theMovie =[[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL fileURLWithPath:self.theVideoPath]];

[self presentMoviePlayerViewControllerAnimated:theMovie];

theMovie.moviePlayer.movieSourceType=MPMovieSourceTypeFile;[theMovie.moviePlayer play];}

//第二種方式

- (void)writeImages:(NSArray *)imagesArray ToMovieAtPath:(NSString *)path withSize:(CGSize)size ?inDuration:(float)duration byFPS:(int32_t)fps{

//Wire the writer:

NSError *error =nil;

AVAssetWriter *videoWriter =[[AVAssetWriter alloc]initWithURL:[NSURL fileURLWithPath:path]fileType:AVFileTypeQuickTimeMovie ?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]);

[videoWriter addInput:videoWriterInput];

//Start a session:

[videoWriter startWriting];

[videoWriter startSessionAtSourceTime:kCMTimeZero];

//Write some samples:

CVPixelBufferRef buffer =NULL;

int frameCount =0;

int imagesCount = [imagesArray count];

float averageTime =duration/imagesCount;

int averageFrame =(int)(averageTime * fps);

for(UIImage *img in imagesArray){

buffer=[self pixelBufferFromCGImage:[img CGImage]size:size];

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)fps);float frameSeconds =CMTimeGetSeconds(frameTime);

NSLog(@"frameCount:%d,kRecordingFPS:%d,frameSeconds:%f",frameCount,fps,frameSeconds);

append_ok = [adaptor appendPixelBuffer:buffer withPresentationTime:frameTime];

if(buffer)

[NSThread sleepForTimeInterval:0.05];}else{

printf("adaptor not ready %d,%d\n", frameCount, j);

[NSThread sleepForTimeInterval:0.1];}

j++;}

if (!append_ok){

printf("error appendingimage %d times %d\n", frameCount, j);}

frameCount = frameCount + averageFrame;}

//Finish the session:

[videoWriterInput markAsFinished];

[videoWriter finishWriting];NSLog(@"finishWriting");}




二:視頻跟音頻的合成

// 混合音樂(lè)

-(void)merge{

// mbp提示框

//? [MBProgressHUD showMessage:@"正在處理中"];

// 路徑

NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

// 聲音來(lái)源

NSURL *audioInputUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"藍(lán)瘦香菇" ofType:@"mp3"]];

// 視頻來(lái)源

NSURL *videoInputUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"2016全球三大超跑宣傳片_超清" ofType:@"mp4"]];

// 最終合成輸出路徑

NSString *outPutFilePath = [documents stringByAppendingPathComponent:@"merge.mp4"];

// 添加合成路徑

NSURL *outputFileUrl = [NSURL fileURLWithPath:outPutFilePath];

// 時(shí)間起點(diǎn)

CMTime nextClistartTime = kCMTimeZero;

// 創(chuàng)建可變的音視頻組合

AVMutableComposition *comosition = [AVMutableComposition composition];

// 視頻采集

AVURLAsset *videoAsset = [[AVURLAsset alloc] initWithURL:videoInputUrl options:nil];

// 視頻時(shí)間范圍

CMTimeRange videoTimeRange = CMTimeRangeMake(kCMTimeZero, videoAsset.duration);

// 視頻通道 枚舉 kCMPersistentTrackID_Invalid = 0

AVMutableCompositionTrack *videoTrack = [comosition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

// 視頻采集通道

AVAssetTrack *videoAssetTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] firstObject];

//? 把采集軌道數(shù)據(jù)加入到可變軌道之中

[videoTrack insertTimeRange:videoTimeRange ofTrack:videoAssetTrack atTime:nextClistartTime error:nil];

// 聲音采集

AVURLAsset *audioAsset = [[AVURLAsset alloc] initWithURL:audioInputUrl options:nil];

// 因?yàn)橐曨l短這里就直接用視頻長(zhǎng)度了,如果自動(dòng)化需要自己寫判斷

CMTimeRange audioTimeRange = videoTimeRange;

// 音頻通道

AVMutableCompositionTrack *audioTrack = [comosition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

// 音頻采集通道

AVAssetTrack *audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];

// 加入合成軌道之中

[audioTrack insertTimeRange:audioTimeRange ofTrack:audioAssetTrack atTime:nextClistartTime error:nil];

// 創(chuàng)建一個(gè)輸出

AVAssetExportSession *assetExport = [[AVAssetExportSession alloc] initWithAsset:comosition presetName:AVAssetExportPresetMediumQuality];

// 輸出類型

assetExport.outputFileType = AVFileTypeQuickTimeMovie;

// 輸出地址

assetExport.outputURL = outputFileUrl;

// 優(yōu)化

assetExport.shouldOptimizeForNetworkUse = YES;

// 合成完畢

[assetExport exportAsynchronouslyWithCompletionHandler:^{

// 回到主線程

dispatch_async(dispatch_get_main_queue(), ^{

// 調(diào)用播放方法? outputFileUrl 這個(gè)就是合成視頻跟音頻的視頻

[self playWithUrl:outputFileUrl];

});

}];

}?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,501評(píng)論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,673評(píng)論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,610評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,939評(píng)論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,668評(píng)論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,004評(píng)論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,001評(píng)論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,173評(píng)論 0 290
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,705評(píng)論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,426評(píng)論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,656評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,139評(píng)論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,833評(píng)論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,247評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,580評(píng)論 1 295
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,371評(píng)論 3 400
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,621評(píng)論 2 380

推薦閱讀更多精彩內(nèi)容