iOS视频编辑之添加音轨的方法

2020-01-21 03:31:21王冬梅


- (AVPlayerItem *)playerItem {
  if (!_currentItem) {
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:self.composition];
    playerItem.videoComposition = self.videoComposition;
    playerItem.audioMix = self.audioMix;
    _currentItem = playerItem;
  }
  return _currentItem;
}

7 播放时调整音量,这里其实和第5步一样,重新配置AVMutableAudioMix参数后赋值给AVPlayerItem,设置音乐音量同理


- (void)setVideoVolume:(CGFloat)volume {
  NSMutableArray *allAudioParams = [NSMutableArray array];
  
  AVMutableAudioMixInputParameters *audioInputParams =
  [AVMutableAudioMixInputParameters audioMixInputParameters];
  [audioInputParams setTrackID:_comTrack1.trackID];
  _videoVolume = volume;
  [audioInputParams setVolume:_videoVolume atTime:kCMTimeZero];
  [allAudioParams addObject:audioInputParams];
  
  AVMutableAudioMixInputParameters *audioInputParams2 =
  [AVMutableAudioMixInputParameters audioMixInputParameters];
  [audioInputParams2 setTrackID:_comTrack2.trackID];
  [audioInputParams2 setVolume:_musicVolume atTime:kCMTimeZero];
  [allAudioParams addObject:audioInputParams2];
  
  AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
  [audioMix setInputParameters:allAudioParams];
  
  [_currentItem setAudioMix:audioMix];
}

导出实现

这里直接使用AVAssetExportSession来导出视频,与设置AVPlayerItem的audioMix属性相同,将audioMix设置给AVAssetExportSession实例即可导出混合的视频了


  NSURL *outputFileUrl = [NSURL fileURLWithPath:outputPath];  
  AVAssetExportSession *_assetExport =[[AVAssetExportSession alloc]initWithAsset:self.composition presetName:AVAssetExportPreset1280x720];
  _assetExport.outputFileType = AVFileTypeMPEG4;
  _assetExport.audioMix = _currentItem.audioMix;
  _assetExport.outputURL = outputFileUrl;
  _assetExport.shouldOptimizeForNetworkUse = YES;  
  [_assetExport exportAsynchronouslyWithCompletionHandler:^{
    //
  }];

最后贴上Demo地址 https://github.com/lucifron1994/VideoMixAudioDemo

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到IOS开发频道。