热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

iOS视频添加背景音乐同时保留原音

本文主要介绍了iOS视频添加背景音乐同时保留原音的实现方法。具有很好的参考价值,下面跟着小编一起来看下吧

话不多说,请看代码:

//抽取原视频的音频与需要的音乐混合 
-(void)addmusic:(id)sender 
{ 
 [MBProgressHUDshowHUDAddedTo:self.viewanimated:YES]; 

 AVMutableComposition *composition =[AVMutableCompositioncomposition]; 
 audioMixParams =[[NSMutableArrayalloc]initWithObjects:nil]; 

 //录制的视频 
 NSURL *video_inputFileUrl =[NSURLfileURLWithPath:self.videoPath]; 
 AVURLAsset *sOngAsset=[AVURLAssetURLAssetWithURL:video_inputFileUrloptions:nil]; 
 CMTime startTime =CMTimeMakeWithSeconds(0,songAsset.duration.timescale); 
 CMTime trackDuration =songAsset.duration; 

 //获取视频中的音频素材 
 [selfsetUpAndAddAudioAtPath:video_inputFileUrltoComposition:compositionstart:startTimedura:trackDurationoffset:CMTimeMake(14*44100,44100)]; 

 //本地要插入的音乐 
 NSString *bundleDirectory =[[NSBundlemainBundle]bundlePath]; 
 NSString *path = [bundleDirectorystringByAppendingPathComponent:@"30secs.mp3"]; 
 NSURL *assetURL2 =[NSURLfileURLWithPath:path]; 
 //获取设置完的本地音乐素材 
 [selfsetUpAndAddAudioAtPath:assetURL2toComposition:compositionstart:startTimedura:trackDurationoffset:CMTimeMake(0,44100)]; 

 //创建一个可变的音频混合 
 AVMutableAudioMix *audioMix =[AVMutableAudioMixaudioMix]; 
 audioMix.inputParameters =[NSArrayarrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数 

 //创建一个输出 
 AVAssetExportSession *exporter =[[AVAssetExportSessionalloc] 
        initWithAsset:composition 
        presetName:AVAssetExportPresetAppleM4A]; 
 exporter.audioMix = audioMix; 
 exporter.outputFileType=@"com.apple.m4a-audio"; 
 NSString* fileName =[NSStringstringWithFormat:@"%@.mov",@"overMix"]; 
 //输出路径 
 NSString *exportFile =[NSStringstringWithFormat:@"%@/%@",[selfgetLibarayPath], fileName]; 

 if([[NSFileManagerdefaultManager]fileExistsAtPath:exportFile]) { 
  [[NSFileManagerdefaultManager]removeItemAtPath:exportFileerror:nil]; 
 } 
 NSLog(@"是否在主线程1%d",[NSThreadisMainThread]); 
 NSLog(@"输出路径===%@",exportFile); 

 NSURL *exportURL =[NSURLfileURLWithPath:exportFile]; 
 exporter.outputURL = exportURL; 
 self.mixURL =exportURL; 

 [exporterexportAsynchronouslyWithCompletionHandler:^{ 
  int exportStatus =(int)exporter.status; 
  switch (exportStatus){ 
   caseAVAssetExportSessionStatusFailed:{ 
    NSError *exportError =exporter.error; 
    NSLog(@"错误,信息: %@", exportError); 
    [MBProgressHUDhideHUDForView:self.viewanimated:YES]; 
    break; 
   } 
   caseAVAssetExportSessionStatusCompleted:{ 
    NSLog(@"是否在主线程2%d",[NSThreadisMainThread]); 
    NSLog(@"成功"); 
    //最终混合 
    [selftheVideoWithMixMusic]; 
    break; 
   } 
  } 
 }]; 
} 

//最终音频和视频混合 
-(void)theVideoWithMixMusic 
{ 
 NSError *error =nil; 
 NSFileManager *fileMgr =[NSFileManagerdefaultManager]; 
 NSString *documentsDirectory =[NSHomeDirectory() 
        stringByAppendingPathComponent:@"Documents"]; 
 NSString *videoOutputPath =[documentsDirectorystringByAppendingPathComponent:@"test_output.mp4"]; 
 if ([fileMgrremoveItemAtPath:videoOutputPatherror:&error]!=YES) { 
  NSLog(@"无法删除文件,错误信息:%@",[error localizedDescription]); 
 } 

 //声音来源路径(最终混合的音频) 
 NSURL *audio_inputFileUrl =self.mixURL; 

 //视频来源路径 
 NSURL *video_inputFileUrl = [NSURLfileURLWithPath:self.videoPath]; 

 //最终合成输出路径 
 NSString *outputFilePath =[documentsDirectorystringByAppendingPathComponent:@"final_video.mp4"]; 
 NSURL *outputFileUrl = [NSURLfileURLWithPath:outputFilePath]; 

 if([[NSFileManagerdefaultManager]fileExistsAtPath:outputFilePath]) 
  [[NSFileManagerdefaultManager]removeItemAtPath:outputFilePatherror:nil]; 

 CMTime nextClipStartTime =kCMTimeZero; 

 //创建可变的音频视频组合 
 AVMutableComposition* mixComposition =[AVMutableCompositioncomposition]; 

 //视频采集 
 AVURLAsset* videoAsset =[[AVURLAssetalloc]initWithURL:video_inputFileUrloptions:nil]; 
 CMTimeRange video_timeRange =CMTimeRangeMake(kCMTimeZero,videoAsset.duration); 
 AVMutableCompositionTrack*a_compositiOnVideoTrack= [mixCompositionaddMutableTrackWithMediaType:AVMediaTypeVideopreferredTrackID:kCMPersistentTrackID_Invalid]; 
 [a_compositionVideoTrackinsertTimeRange:video_timeRangeofTrack:[[videoAssettracksWithMediaType:AVMediaTypeVideo]objectAtIndex:0]atTime:nextClipStartTimeerror:nil]; 

 //声音采集 
 AVURLAsset* audioAsset =[[AVURLAssetalloc]initWithURL:audio_inputFileUrloptions:nil]; 
 CMTimeRange audio_timeRange =CMTimeRangeMake(kCMTimeZero,videoAsset.duration);//声音长度截取范围==视频长度 
 AVMutableCompositionTrack*b_compositiOnAudioTrack= [mixCompositionaddMutableTrackWithMediaType:AVMediaTypeAudiopreferredTrackID:kCMPersistentTrackID_Invalid]; 
 [b_compositionAudioTrackinsertTimeRange:audio_timeRangeofTrack:[[audioAssettracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0]atTime:nextClipStartTimeerror:nil]; 

 //创建一个输出 
 AVAssetExportSession* _assetExport =[[AVAssetExportSessionalloc]initWithAsset:mixCompositionpresetName:AVAssetExportPresetMediumQuality]; 
 _assetExport.outputFileType =AVFileTypeQuickTimeMovie; 
 _assetExport.outputURL =outputFileUrl; 
 _assetExport.shouldOptimizeForNetworkUse=YES; 
 self.theEndVideoURL=outputFileUrl; 

 [_assetExportexportAsynchronouslyWithCompletionHandler: 
 ^(void ) { 
  [MBProgressHUDhideHUDForView:self.viewanimated:YES]; 
  //播放 
  NSURL*url = [NSURLfileURLWithPath:outputFilePath]; 
  MPMoviePlayerViewController *theMovie =[[MPMoviePlayerViewControlleralloc]initWithContentURL:url]; 
  [selfpresentMoviePlayerViewControllerAnimated:theMovie]; 
  theMovie.moviePlayer.movieSourceType=MPMovieSourceTypeFile; 
  [theMovie.moviePlayerplay]; 
 } 
 ]; 
 NSLog(@"完成!输出路径==%@",outputFilePath); 
} 

//通过文件路径建立和添加音频素材 
- (void)setUpAndAddAudioAtPath:(NSURL*)assetURLtoComposition:(AVMutableComposition*)composition start:(CMTime)startdura:(CMTime)duraoffset:(CMTime)offset{ 

 AVURLAsset *sOngAsset=[AVURLAssetURLAssetWithURL:assetURLoptions:nil]; 

 AVMutableCompositionTrack *track =[compositionaddMutableTrackWithMediaType:AVMediaTypeAudiopreferredTrackID:kCMPersistentTrackID_Invalid]; 
 AVAssetTrack *sourceAudioTrack =[[songAssettracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0]; 

 NSError *error =nil; 
 BOOL ok =NO; 

 CMTime startTime = start; 
 CMTime trackDuration = dura; 
 CMTimeRange tRange =CMTimeRangeMake(startTime,trackDuration); 

 //设置音量 
 //AVMutableAudioMixInputParameters(输入参数可变的音频混合) 
 //audioMixInputParametersWithTrack(音频混音输入参数与轨道) 
 AVMutableAudioMixInputParameters *trackMix =[AVMutableAudioMixInputParametersaudioMixInputParametersWithTrack:track]; 
 [trackMixsetVolume:0.8fatTime:startTime]; 

 //素材加入数组 
 [audioMixParamsaddObject:trackMix]; 

 //Insert audio into track //offsetCMTimeMake(0, 44100) 
 ok = [trackinsertTimeRange:tRangeofTrack:sourceAudioTrackatTime:kCMTimeInvaliderror:&error]; 
} 

 #pragma mark - 保存路径 
-(NSString*)getLibarayPath 
{ 
 NSFileManager *fileManager =[NSFileManagerdefaultManager]; 
 NSArray* paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); 
 NSString* path = [pathsobjectAtIndex:0]; 
 NSString *movDirectory = [pathstringByAppendingPathComponent:@"tmpMovMix"]; 
 [fileManagercreateDirectoryAtPath:movDirectorywithIntermediateDirectories:YESattributes:nilerror:nil]; 
 return movDirectory; 
} 

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!


推荐阅读
  • HDFS2.x新特性
    一、集群间数据拷贝scp实现两个远程主机之间的文件复制scp-rhello.txtroothadoop103:useratguiguhello.txt推pushscp-rr ... [详细]
  • 如何在服务器主机上实现文件共享的方法和工具
    本文介绍了在服务器主机上实现文件共享的方法和工具,包括Linux主机和Windows主机的文件传输方式,Web运维和FTP/SFTP客户端运维两种方式,以及使用WinSCP工具将文件上传至Linux云服务器的操作方法。此外,还介绍了在迁移过程中需要安装迁移Agent并输入目的端服务器所在华为云的AK/SK,以及主机迁移服务会收集的源端服务器信息。 ... [详细]
  • SpringBoot整合SpringSecurity+JWT实现单点登录
    SpringBoot整合SpringSecurity+JWT实现单点登录,Go语言社区,Golang程序员人脉社 ... [详细]
  • LVS实现负载均衡的原理LVS负载均衡负载均衡集群是LoadBalance集群。是一种将网络上的访问流量分布于各个节点,以降低服务器压力,更好的向客户端 ... [详细]
  • 本文详细介绍了在Centos7上部署安装zabbix5.0的步骤和注意事项,包括准备工作、获取所需的yum源、关闭防火墙和SELINUX等。提供了一步一步的操作指南,帮助读者顺利完成安装过程。 ... [详细]
  • GSIOpenSSH PAM_USER 安全绕过漏洞
    漏洞名称:GSI-OpenSSHPAM_USER安全绕过漏洞CNNVD编号:CNNVD-201304-097发布时间:2013-04-09 ... [详细]
  • 本文介绍了在RHEL 7中的系统日志管理和网络管理。系统日志管理包括rsyslog和systemd-journal两种日志服务,分别介绍了它们的特点、配置文件和日志查询方式。网络管理主要介绍了使用nmcli命令查看和配置网络接口的方法,包括查看网卡信息、添加、修改和删除配置文件等操作。 ... [详细]
  • Python脚本编写创建输出数据库并添加模型和场数据的方法
    本文介绍了使用Python脚本编写创建输出数据库并添加模型数据和场数据的方法。首先导入相应模块,然后创建输出数据库并添加材料属性、截面、部件实例、分析步和帧、节点和单元等对象。接着向输出数据库中添加场数据和历程数据,本例中只添加了节点位移。最后保存数据库文件并关闭文件。文章还提供了部分代码和Abaqus操作步骤。另外,作者还建立了关于Abaqus的学习交流群,欢迎加入并提问。 ... [详细]
  •     这里使用自己编译的hadoop-2.7.0版本部署在windows上,记得几年前,部署hadoop需要借助于cygwin,还需要开启ssh服务,最近发现,原来不需要借助cy ... [详细]
  • 大坑|左上角_pycharm连接服务器同步写代码(图文详细过程)
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了pycharm连接服务器同步写代码(图文详细过程)相关的知识,希望对你有一定的参考价值。pycharm连接服务 ... [详细]
  • Hadoop2.6.0 + 云centos +伪分布式只谈部署
    3.0.3玩不好,现将2.6.0tar.gz上传到usr,chmod-Rhadoop:hadophadoop-2.6.0,rm掉3.0.32.在etcp ... [详细]
  • linux 禁止指定ip访问
    linux中如何禁止指定的ip访问呢?比如被别人暴力破解,被别人使用不同的密码尝试登录:所以我想直接禁用这些ip的访问.怎么办呢?解决方案:修改配置文件etchosts.deny把 ... [详细]
  • 一、修改注册表去掉桌面图标小箭头1按下win+R组合快捷键,打开windows10系统的“运行”窗口,输入“regedit”,打开注册表编辑器,找到HKEY_CLASSES_ROOT\lnkfi ... [详细]
  • Django + Ansible 主机管理(有源码)
    本文给大家介绍如何利用DjangoAnsible进行Web项目管理。Django介绍一个可以使Web开发工作愉快并且高效的Web开发框架,能够以最小的代价构建和维护高 ... [详细]
  • hadoop1.2.1文档中这样写:Nowcheckthatyoucansshtothelocalhostwithoutapassphrase:$sshlocalhostIfyou ... [详细]
author-avatar
手机用户2502931035
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有