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

  1. //抽取原视频的音频与需要的音乐混合  
  2. -(void)addmusic:(id)sender  
  3. {  
  4.    [MBProgressHUDshowHUDAddedTo:self.viewanimated:YES];  
  5.     
  6.    AVMutableComposition *composition =[AVMutableCompositioncomposition];  
  7.    audioMixParams =[[NSMutableArrayalloc]initWithObjects:nil];  
  8.      
  9.    //录制的视频  
  10.    NSURL *video_inputFileUrl =[NSURLfileURLWithPath:self.videoPath];  
  11.    AVURLAsset *songAsset =[AVURLAssetURLAssetWithURL:video_inputFileUrloptions:nil];  
  12.    CMTime startTime =CMTimeMakeWithSeconds(0,songAsset.duration.timescale);  
  13.    CMTime trackDuration =songAsset.duration;  
  14.      
  15.    //获取视频中的音频素材  
  16.    [selfsetUpAndAddAudioAtPath:video_inputFileUrltoComposition:compositionstart:startTimedura:trackDurationoffset:CMTimeMake(14*44100,44100)];  
  17.      
  18.    //本地要插入的音乐  
  19.    NSString *bundleDirectory =[[NSBundlemainBundle]bundlePath];  
  20.    NSString *path = [bundleDirectorystringByAppendingPathComponent:@"30secs.mp3"];  
  21.    NSURL *assetURL2 =[NSURLfileURLWithPath:path];  
  22.    //获取设置完的本地音乐素材  
  23.    [selfsetUpAndAddAudioAtPath:assetURL2toComposition:compositionstart:startTimedura:trackDurationoffset:CMTimeMake(0,44100)];  
  24.      
  25.    //创建一个可变的音频混合  
  26.    AVMutableAudioMix *audioMix =[AVMutableAudioMixaudioMix];  
  27.    audioMix.inputParameters =[NSArrayarrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数  
  28.      
  29.    //创建一个输出  
  30.    AVAssetExportSession *exporter =[[AVAssetExportSessionalloc]  
  31.                                 initWithAsset:composition  
  32.                                 presetName:AVAssetExportPresetAppleM4A];  
  33.    exporter.audioMix = audioMix;  
  34.    exporter.outputFileType=@"com.apple.m4a-audio";  
  35.    NSString* fileName =[NSStringstringWithFormat:@"%@.mov",@"overMix"];  
  36.    //输出路径  
  37.    NSString *exportFile =[NSStringstringWithFormat:@"%@/%@",[selfgetLibarayPath], fileName];  
  38.      
  39.    if([[NSFileManagerdefaultManager]fileExistsAtPath:exportFile]) {  
  40.       [[NSFileManagerdefaultManager]removeItemAtPath:exportFileerror:nil];  
  41.     }  
  42.    NSLog(@"是否在主线程1%d",[NSThreadisMainThread]);  
  43.    NSLog(@"输出路径===%@",exportFile);  
  44.      
  45.    NSURL *exportURL =[NSURLfileURLWithPath:exportFile];  
  46.    exporter.outputURL = exportURL;  
  47.    self.mixURL =exportURL;  
  48.      
  49.    [exporterexportAsynchronouslyWithCompletionHandler:^{  
  50.        int exportStatus =(int)exporter.status;  
  51.        switch (exportStatus){  
  52.           caseAVAssetExportSessionStatusFailed:{  
  53.              NSError *exportError =exporter.error;  
  54.               NSLog(@"错误,信息: %@", exportError);  
  55.              [MBProgressHUDhideHUDForView:self.viewanimated:YES];  
  56.              break;  
  57.            }  
  58.           caseAVAssetExportSessionStatusCompleted:{  
  59.              NSLog(@"是否在主线程2%d",[NSThreadisMainThread]);  
  60.               NSLog(@"成功");  
  61.              //最终混合  
  62.               [selftheVideoWithMixMusic];  
  63.              break;  
  64.            }  
  65.        }  
  66.     }];  
  67.   
  68. }  
  69.   
  70. //最终音频和视频混合  
  71. -(void)theVideoWithMixMusic  
  72. {  
  73.    NSError *error =nil;  
  74.    NSFileManager *fileMgr =[NSFileManagerdefaultManager];  
  75.    NSString *documentsDirectory =[NSHomeDirectory()  
  76.                               stringByAppendingPathComponent:@"Documents"];  
  77.    NSString *videoOutputPath =[documentsDirectorystringByAppendingPathComponent:@"test_output.mp4"];  
  78.    if ([fileMgrremoveItemAtPath:videoOutputPatherror:&error]!=YES) {  
  79.       NSLog(@"无法删除文件,错误信息:%@",[error localizedDescription]);  
  80.     }  
  81.      
  82.    //声音来源路径(最终混合的音频)  
  83.    NSURL   *audio_inputFileUrl =self.mixURL;  
  84.      
  85.    //视频来源路径  
  86.    NSURL   *video_inputFileUrl = [NSURLfileURLWithPath:self.videoPath];  
  87.      
  88.    //最终合成输出路径  
  89.    NSString *outputFilePath =[documentsDirectorystringByAppendingPathComponent:@"final_video.mp4"];  
  90.    NSURL   *outputFileUrl = [NSURLfileURLWithPath:outputFilePath];  
  91.      
  92.    if([[NSFileManagerdefaultManager]fileExistsAtPath:outputFilePath])  
  93.       [[NSFileManagerdefaultManager]removeItemAtPath:outputFilePatherror:nil];  
  94.      
  95.    CMTime nextClipStartTime =kCMTimeZero;  
  96.      
  97.    //创建可变的音频视频组合  
  98.    AVMutableComposition* mixComposition =[AVMutableCompositioncomposition];  
  99.      
  100.    //视频采集  
  101.    AVURLAsset* videoAsset =[[AVURLAssetalloc]initWithURL:video_inputFileUrloptions:nil];  
  102.    CMTimeRange video_timeRange =CMTimeRangeMake(kCMTimeZero,videoAsset.duration);  
  103.    AVMutableCompositionTrack*a_compositionVideoTrack = [mixCompositionaddMutableTrackWithMediaType:AVMediaTypeVideopreferredTrackID:kCMPersistentTrackID_Invalid];  
  104.    [a_compositionVideoTrackinsertTimeRange:video_timeRangeofTrack:[[videoAssettracksWithMediaType:AVMediaTypeVideo]objectAtIndex:0]atTime:nextClipStartTimeerror:nil];  
  105.      
  106.    //声音采集  
  107.    AVURLAsset* audioAsset =[[AVURLAssetalloc]initWithURL:audio_inputFileUrloptions:nil];  
  108.    CMTimeRange audio_timeRange =CMTimeRangeMake(kCMTimeZero,videoAsset.duration);//声音长度截取范围==视频长度  
  109.    AVMutableCompositionTrack*b_compositionAudioTrack = [mixCompositionaddMutableTrackWithMediaType:AVMediaTypeAudiopreferredTrackID:kCMPersistentTrackID_Invalid];  
  110.    [b_compositionAudioTrackinsertTimeRange:audio_timeRangeofTrack:[[audioAssettracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0]atTime:nextClipStartTimeerror:nil];  
  111.      
  112.    //创建一个输出  
  113.    AVAssetExportSession* _assetExport =[[AVAssetExportSessionalloc]initWithAsset:mixCompositionpresetName:AVAssetExportPresetMediumQuality];  
  114.    _assetExport.outputFileType =AVFileTypeQuickTimeMovie;  
  115.    _assetExport.outputURL =outputFileUrl;  
  116.    _assetExport.shouldOptimizeForNetworkUse=YES;  
  117.    self.theEndVideoURL=outputFileUrl;  
  118.      
  119.    [_assetExportexportAsynchronouslyWithCompletionHandler:  
  120.     ^(void ) {  
  121.        [MBProgressHUDhideHUDForView:self.viewanimated:YES];  
  122.        //播放  
  123.         NSURL*url = [NSURLfileURLWithPath:outputFilePath];  
  124.        MPMoviePlayerViewController *theMovie =[[MPMoviePlayerViewControlleralloc]initWithContentURL:url];  
  125.        [selfpresentMoviePlayerViewControllerAnimated:theMovie];  
  126.        theMovie.moviePlayer.movieSourceType=MPMovieSourceTypeFile;  
  127.        [theMovie.moviePlayerplay];  
  128.     }  
  129.     ];  
  130.    NSLog(@"完成!输出路径==%@",outputFilePath);  
  131. }  
  132.   
  133. //通过文件路径建立和添加音频素材  
  134. - (void)setUpAndAddAudioAtPath:(NSURL*)assetURLtoComposition:(AVMutableComposition*)composition start:(CMTime)startdura:(CMTime)duraoffset:(CMTime)offset{  
  135.      
  136.    AVURLAsset *songAsset =[AVURLAssetURLAssetWithURL:assetURLoptions:nil];  
  137.      
  138.    AVMutableCompositionTrack *track =[compositionaddMutableTrackWithMediaType:AVMediaTypeAudiopreferredTrackID:kCMPersistentTrackID_Invalid];  
  139.    AVAssetTrack *sourceAudioTrack =[[songAssettracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0];  
  140.      
  141.    NSError *error =nil;  
  142.    BOOL ok =NO;  
  143.      
  144.    CMTime startTime = start;  
  145.    CMTime trackDuration = dura;  
  146.    CMTimeRange tRange =CMTimeRangeMake(startTime,trackDuration);  
  147.      
  148.    //设置音量  
  149.    //AVMutableAudioMixInputParameters(输入参数可变的音频混合)  
  150.    //audioMixInputParametersWithTrack(音频混音输入参数与轨道)  
  151.    AVMutableAudioMixInputParameters *trackMix =[AVMutableAudioMixInputParametersaudioMixInputParametersWithTrack:track];  
  152.     [trackMixsetVolume:0.8fatTime:startTime];  
  153.      
  154.    //素材加入数组  
  155.    [audioMixParamsaddObject:trackMix];  
  156.      
  157.    //Insert audio into track  //offsetCMTimeMake(0, 44100)  
  158.     ok = [trackinsertTimeRange:tRangeofTrack:sourceAudioTrackatTime:kCMTimeInvaliderror:&error];  
  159. }  
  160.   
  161. #pragma mark - 保存路径  
  162. -(NSString*)getLibarayPath  
  163. {  
  164.    NSFileManager *fileManager =[NSFileManagerdefaultManager];  
  165.      
  166.    NSArray* paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);  
  167.    NSString* path = [pathsobjectAtIndex:0];  
  168.      
  169.    NSString *movDirectory = [pathstringByAppendingPathComponent:@"tmpMovMix"];  
  170.      
  171.    [fileManagercreateDirectoryAtPath:movDirectorywithIntermediateDirectories:YESattributes:nilerror:nil];  
  172.      
  173.    return movDirectory;  
  174.    
  175. }  
//抽取原视频的音频与需要的音乐混合
-(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;
 
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值