AVComposition 視頻組合

AVComposition使用

一男窟、理解

對象AVComposition

AVComposition繼承自AVAsset,通過其可變對象將來自多個媒體資源數(shù)據(jù)組合在一起顯示牺六。

AVComposition是有資源軌道(AVMutableCompositionTrack)信息組成,如視頻資源中包含了音頻軌道和視頻軌道盗胀;每個軌道是有軌道片段(AVCompositionTrackSegment)組成宅荤。

AVMutableComposition

//生成一個空的可變組合對象

+ (instancetype)composition;

//生成一個空的可變組合對象,并且可以設(shè)置一些信息如:AVURLAssetPreferPreciseDurationAndTimingKey 精確的時間設(shè)置

+ (instancetype)compositionWithURLAssetInitializationOptions:(nullable NSDictionary<NSString *, id> *)URLAssetInitializationOptions;

//獲取軌道資源信息

@property (nonatomic, readonly) NSArray<AVMutableCompositionTrack *> *tracks;

//組合資源輸出的尺寸

@property (nonatomic) CGSize naturalSize;

//將一段指定的Asset資源(只能是 AVURLAsset 和 AVComposition)插入到軌道指定時間點

- (BOOL)insertTimeRange:(CMTimeRange)timeRange ofAsset:(AVAsset *)asset atTime:(CMTime)startTime error:(NSError * _Nullable * _Nullable)outError;

//在合成軌道上添加一段空timeRange

- (void)insertEmptyTimeRange:(CMTimeRange)timeRange;

//合成軌道上刪除指定timeRange

- (void)removeTimeRange:(CMTimeRange)timeRange;

// 添加空的視頻或音頻軌道

// mediaType:添加軌道的媒體類型

// preferredTrackID:指定新軌道的首選軌道ID惫确。如果你不提供一個明確的就設(shè)置成kCMPersistentTrackID_Invalid昧诱,會自動生成一個唯一的TrackID,否則你就需要提供一個未被使用過的一個TrackID

- (nullable AVMutableCompositionTrack *)addMutableTrackWithMediaType:(AVMediaType)mediaType preferredTrackID:(CMPersistentTrackID)preferredTrackID;

image

二、使用

簡單的使用方法;

1. 創(chuàng)建可變組合對象


AVMutableComposition *composition = [AVMutableComposition composition];

2. 創(chuàng)建視頻和音頻軌道


AVMutableCompositionTrack *videoCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

AVMutableCompositionTrack *audioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

3. 插入指定的視頻軌道和音頻軌道


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

[videoCompositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:videoTrack atTime:kCMTimeZero error:nil];

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

[audioCompositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAssetTrack.duration) ofTrack:audioAssetTrack atTime:kCMTimeZero error:nil];

4. 導(dǎo)出組合后的媒體資源


NSURL *videoLocalPath = [NSURL fileURLWithPath:outputPath];

AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:composition presetName:AVAssetExportPresetMediumQuality];

exportSession.outputFileType = AVFileTypeQuickTimeMovie; // 導(dǎo)出資源類型

exportSession.outputURL = videoLocalPath; // 導(dǎo)出資源路徑

exportSession.shouldOptimizeForNetworkUse = YES; // 導(dǎo)出資源針對網(wǎng)絡(luò)加載優(yōu)化

[exportSession exportAsynchronouslyWithCompletionHandler:^{

  dispatch_async(dispatch_get_main_queue(), ^{

      //導(dǎo)出完成

      if (exportSession.status == AVAssetExportSessionStatusCompleted ) {

          if (successBlock) {

              successBlock(exportSession.outputURL);

          }

      } else {

          NSLog(@"視頻合成失敗--%@",exportSession.error);

          if (successBlock) {

              successBlock(exportSession.error);

          }

      }

  });

}];

三、高級媒體組合

媒體資源組合時也可以對各個媒體資源自定義處理。

AVMutableVideoComposition

使用 AVMutableVideoComposition 可以直接處理視頻的軌道崖技,通過它輸出視頻時還可以控制輸出的尺寸、縮放比例装诡、幀率;

image

// 生成一個videoComposition

+ (AVMutableVideoComposition *)videoComposition;

// 幀率 必須設(shè)置否則crash

@property (nonatomic) CMTime frameDuration;

// 渲染尺寸 必須設(shè)置否則crash

@property (nonatomic) CGSize renderSize;

// 設(shè)置渲染縮放比

@property (nonatomic) float renderScale

// 媒體處理指令集

@property (nonatomic, copy) NSArray<id <AVVideoCompositionInstruction>> *instructions;

// 通過使用Core Animation對視頻做一些處理肄程,如添加水印等

@property (nonatomic, retain, nullable) AVVideoCompositionCoreAnimationTool *animationTool;

AVMutableVideoCompositionInstruction

視頻指令集


// 生成視頻指令集

+ (instancetype)videoCompositionInstruction;

// 設(shè)置指令集作用的timeRange

@property (nonatomic, assign) CMTimeRange timeRange;

// 設(shè)置媒體背景顏色

@property (nonatomic, retain, nullable) __attribute__((NSObject)) CGColorRef backgroundColor;

// 媒體layer層指令集

@property (nonatomic, copy) NSArray<AVVideoCompositionLayerInstruction *> *layerInstructions;

AVMutableVideoCompositionLayerInstruction

// 根據(jù)媒體軌道信息生成layer 指令對象

+ (instancetype)videoCompositionLayerInstructionWithAssetTrack:(AVAssetTrack *)track;

// 旋轉(zhuǎn)媒體資源

- (void)setTransform:(CGAffineTransform)transform atTime:(CMTime)time;

- - (void)setTransformRampFromStartTransform:(CGAffineTransform)startTransform toEndTransform:(CGAffineTransform)endTransform timeRange:(CMTimeRange)timeRange;

// 設(shè)置透明度

- (void)setOpacityRampFromStartOpacity:(float)startOpacity toEndOpacity:(float)endOpacity timeRange:(CMTimeRange)timeRange;

- (void)setOpacity:(float)opacity atTime:(CMTime)time;

-

AVMutableAudioMix
image

// 生成一個空的音頻管理對象

+ (instancetype)audioMix;

// 設(shè)置混合音頻處理集

@property (nonatomic, copy) NSArray<AVAudioMixInputParameters *> *inputParameters;

AVMutableAudioMixInputParameters

// 根據(jù)音頻軌道生成一個混音輸入?yún)?shù)對象

+ (instancetype)audioMixInputParametersWithTrack:(nullable AVAssetTrack *)track;

// 設(shè)置音頻的質(zhì)量

/*

    AVAudioTimePitchAlgorithmLowQualityZeroLatency 低質(zhì)量

    AVAudioTimePitchAlgorithmTimeDomain 標準質(zhì)量

    AVAudioTimePitchAlgorithmSpectral 高音質(zhì)

    AVAudioTimePitchAlgorithmVarispeed 無損音質(zhì)

*/

@property (nonatomic, copy, nullable) AVAudioTimePitchAlgorithm audioTimePitchAlgorithm API_AVAILABLE(macos(10.10), ios(7.0), tvos(9.0), watchos(1.0));

// 設(shè)置混音中音量寺惫、音量漸變

- (void)setVolumeRampFromStartVolume:(float)startVolume toEndVolume:(float)endVolume timeRange:(CMTimeRange)timeRange;

- (void)setVolume:(float)volume atTime:(CMTime)time;

](https://upload-images.jianshu.io/upload_images/3817688-7ebc41911d5645bc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

二、使用

簡單的使用方法;

1. 創(chuàng)建可變組合對象


AVMutableComposition *composition = [AVMutableComposition composition];

2. 創(chuàng)建視頻和音頻軌道


AVMutableCompositionTrack *videoCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

AVMutableCompositionTrack *audioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

3. 插入指定的視頻軌道和音頻軌道


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

[videoCompositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:videoTrack atTime:kCMTimeZero error:nil];

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

[audioCompositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAssetTrack.duration) ofTrack:audioAssetTrack atTime:kCMTimeZero error:nil];

4. 導(dǎo)出組合后的媒體資源


NSURL *videoLocalPath = [NSURL fileURLWithPath:outputPath];

AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:composition presetName:AVAssetExportPresetMediumQuality];

exportSession.outputFileType = AVFileTypeQuickTimeMovie; // 導(dǎo)出資源類型

exportSession.outputURL = videoLocalPath; // 導(dǎo)出資源路徑

exportSession.shouldOptimizeForNetworkUse = YES; // 導(dǎo)出資源針對網(wǎng)絡(luò)加載優(yōu)化

[exportSession exportAsynchronouslyWithCompletionHandler:^{

  dispatch_async(dispatch_get_main_queue(), ^{

      //導(dǎo)出完成

      if (exportSession.status == AVAssetExportSessionStatusCompleted ) {

          if (successBlock) {

              successBlock(exportSession.outputURL);

          }

      } else {

          NSLog(@"視頻合成失敗--%@",exportSession.error);

          if (successBlock) {

              successBlock(exportSession.error);

          }

      }

  });

}];

三锰镀、高級媒體組合

媒體資源組合時也可以對各個媒體資源自定義處理憾筏。

AVMutableVideoComposition

使用 AVMutableVideoComposition 可以直接處理視頻的軌道刨肃,通過它輸出視頻時還可以控制輸出的尺寸、縮放比例桅打、幀率站绪;

image

// 生成一個videoComposition

+ (AVMutableVideoComposition *)videoComposition;

// 幀率 必須設(shè)置否則crash

@property (nonatomic) CMTime frameDuration;

// 渲染尺寸 必須設(shè)置否則crash

@property (nonatomic) CGSize renderSize;

// 設(shè)置渲染縮放比

@property (nonatomic) float renderScale

// 媒體處理指令集

@property (nonatomic, copy) NSArray<id <AVVideoCompositionInstruction>> *instructions;

// 通過使用Core Animation對視頻做一些處理锰蓬,如添加水印等

@property (nonatomic, retain, nullable) AVVideoCompositionCoreAnimationTool *animationTool;

AVMutableVideoCompositionInstruction

視頻指令集


// 生成視頻指令集

+ (instancetype)videoCompositionInstruction;

// 設(shè)置指令集作用的timeRange

@property (nonatomic, assign) CMTimeRange timeRange;

// 設(shè)置媒體背景顏色

@property (nonatomic, retain, nullable) __attribute__((NSObject)) CGColorRef backgroundColor;

// 媒體layer層指令集

@property (nonatomic, copy) NSArray<AVVideoCompositionLayerInstruction *> *layerInstructions;

AVMutableVideoCompositionLayerInstruction

// 根據(jù)媒體軌道信息生成layer 指令對象

+ (instancetype)videoCompositionLayerInstructionWithAssetTrack:(AVAssetTrack *)track;

// 旋轉(zhuǎn)媒體資源

- (void)setTransform:(CGAffineTransform)transform atTime:(CMTime)time;

- - (void)setTransformRampFromStartTransform:(CGAffineTransform)startTransform toEndTransform:(CGAffineTransform)endTransform timeRange:(CMTimeRange)timeRange;

// 設(shè)置透明度

- (void)setOpacityRampFromStartOpacity:(float)startOpacity toEndOpacity:(float)endOpacity timeRange:(CMTimeRange)timeRange;

- (void)setOpacity:(float)opacity atTime:(CMTime)time;

-

AVMutableAudioMix
image

// 生成一個空的音頻管理對象

+ (instancetype)audioMix;

// 設(shè)置混合音頻處理集

@property (nonatomic, copy) NSArray<AVAudioMixInputParameters *> *inputParameters;

AVMutableAudioMixInputParameters

// 根據(jù)音頻軌道生成一個混音輸入?yún)?shù)對象

+ (instancetype)audioMixInputParametersWithTrack:(nullable AVAssetTrack *)track;

// 設(shè)置音頻的質(zhì)量

/*

    AVAudioTimePitchAlgorithmLowQualityZeroLatency 低質(zhì)量

    AVAudioTimePitchAlgorithmTimeDomain 標準質(zhì)量

    AVAudioTimePitchAlgorithmSpectral 高音質(zhì)

    AVAudioTimePitchAlgorithmVarispeed 無損音質(zhì)

*/

@property (nonatomic, copy, nullable) AVAudioTimePitchAlgorithm audioTimePitchAlgorithm API_AVAILABLE(macos(10.10), ios(7.0), tvos(9.0), watchos(1.0));

// 設(shè)置混音中音量、音量漸變

- (void)setVolumeRampFromStartVolume:(float)startVolume toEndVolume:(float)endVolume timeRange:(CMTimeRange)timeRange;

- (void)setVolume:(float)volume atTime:(CMTime)time;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子饲握,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進店門蜂莉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蚁滋,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵笋妥,是天一觀的道長月帝。 經(jīng)常有香客問我嚷辅,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上爽雄,老公的妹妹穿的比我還像新娘焰檩。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布雄卷。 她就那樣靜靜地躺著雳灾,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天衷咽,我揣著相機與錄音卖词,去河邊找鬼此蜈。 笑死跺嗽,一個胖子當著我的面吹牛楣导,可吹牛的內(nèi)容都是我干的巴元。 我是一名探鬼主播佳谦,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼娄涩!你這毒婦竟也來了窗怒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤蓄拣,失蹤者是張志新(化名)和其女友劉穎扬虚,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體球恤,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡辜昵,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了咽斧。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片堪置。...
    茶點故事閱讀 40,503評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖收厨,靈堂內(nèi)的尸體忽然破棺而出晋柱,到底是詐尸還是另有隱情,我是刑警寧澤诵叁,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布雁竞,位于F島的核電站,受9級特大地震影響拧额,放射性物質(zhì)發(fā)生泄漏碑诉。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一侥锦、第九天 我趴在偏房一處隱蔽的房頂上張望进栽。 院中可真熱鬧,春花似錦恭垦、人聲如沸快毛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽唠帝。三九已至屯掖,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間襟衰,已是汗流浹背贴铜。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留瀑晒,地道東北人绍坝。 一個月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像苔悦,于是被迫代替她去往敵國和親轩褐。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,512評論 2 359

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