iOS video adds background music while retaining the original sound

  • 2021-12-12 06:01:41
  • OfStack

Without saying much, please look at the code:


// Extract the audio of the original video and mix it with the required music  
-(void)addmusic:(id)sender 
{ 
 [MBProgressHUDshowHUDAddedTo:self.viewanimated:YES]; 

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

 // Recorded video  
 NSURL *video_inputFileUrl =[NSURLfileURLWithPath:self.videoPath]; 
 AVURLAsset *songAsset =[AVURLAssetURLAssetWithURL:video_inputFileUrloptions:nil]; 
 CMTime startTime =CMTimeMakeWithSeconds(0,songAsset.duration.timescale); 
 CMTime trackDuration =songAsset.duration; 

 // Get audio material from video  
 [selfsetUpAndAddAudioAtPath:video_inputFileUrltoComposition:compositionstart:startTimedura:trackDurationoffset:CMTimeMake(14*44100,44100)]; 

 // Music to Insert Locally  
 NSString *bundleDirectory =[[NSBundlemainBundle]bundlePath]; 
 NSString *path = [bundleDirectorystringByAppendingPathComponent:@"30secs.mp3"]; 
 NSURL *assetURL2 =[NSURLfileURLWithPath:path]; 
 // Get the set local music material  
 [selfsetUpAndAddAudioAtPath:assetURL2toComposition:compositionstart:startTimedura:trackDurationoffset:CMTimeMake(0,44100)]; 

 // Create 1 Variable audio mixing  
 AVMutableAudioMix *audioMix =[AVMutableAudioMixaudioMix]; 
 audioMix.inputParameters =[NSArrayarrayWithArray:audioMixParams];// Fetch the processed audio track parameters from the array  

 // Create 1 Output  
 AVAssetExportSession *exporter =[[AVAssetExportSessionalloc] 
        initWithAsset:composition 
        presetName:AVAssetExportPresetAppleM4A]; 
 exporter.audioMix = audioMix; 
 exporter.outputFileType=@"com.apple.m4a-audio"; 
 NSString* fileName =[NSStringstringWithFormat:@"%@.mov",@"overMix"]; 
 // Output path  
 NSString *exportFile =[NSStringstringWithFormat:@"%@/%@",[selfgetLibarayPath], fileName]; 

 if([[NSFileManagerdefaultManager]fileExistsAtPath:exportFile]) { 
  [[NSFileManagerdefaultManager]removeItemAtPath:exportFileerror:nil]; 
 } 
 NSLog(@" Is it in the main thread 1%d",[NSThreadisMainThread]); 
 NSLog(@" Output path ===%@",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(@" Error, message : %@", exportError); 
    [MBProgressHUDhideHUDForView:self.viewanimated:YES]; 
    break; 
   } 
   caseAVAssetExportSessionStatusCompleted:{ 
    NSLog(@" Is it in the main thread 2%d",[NSThreadisMainThread]); 
    NSLog(@" Success "); 
    // Final mixing  
    [selftheVideoWithMixMusic]; 
    break; 
   } 
  } 
 }]; 
} 

// Final audio and video mixing  
-(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(@" Unable to delete file, error message: %@",[error localizedDescription]); 
 } 

 // Sound source path (final mixed audio)  
 NSURL *audio_inputFileUrl =self.mixURL; 

 // Video source path  
 NSURL *video_inputFileUrl = [NSURLfileURLWithPath:self.videoPath]; 

 // Final composite output path  
 NSString *outputFilePath =[documentsDirectorystringByAppendingPathComponent:@"final_video.mp4"]; 
 NSURL *outputFileUrl = [NSURLfileURLWithPath:outputFilePath]; 

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

 CMTime nextClipStartTime =kCMTimeZero; 

 // Creating Variable Audio-Video Combinations  
 AVMutableComposition* mixComposition =[AVMutableCompositioncomposition]; 

 // Video capture  
 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]; 

 // Acoustic acquisition  
 AVURLAsset* audioAsset =[[AVURLAssetalloc]initWithURL:audio_inputFileUrloptions:nil]; 
 CMTimeRange audio_timeRange =CMTimeRangeMake(kCMTimeZero,videoAsset.duration);// Sound length interception range == Video length  
 AVMutableCompositionTrack*b_compositionAudioTrack = [mixCompositionaddMutableTrackWithMediaType:AVMediaTypeAudiopreferredTrackID:kCMPersistentTrackID_Invalid]; 
 [b_compositionAudioTrackinsertTimeRange:audio_timeRangeofTrack:[[audioAssettracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0]atTime:nextClipStartTimeerror:nil]; 

 // Create 1 Output  
 AVAssetExportSession* _assetExport =[[AVAssetExportSessionalloc]initWithAsset:mixCompositionpresetName:AVAssetExportPresetMediumQuality]; 
 _assetExport.outputFileType =AVFileTypeQuickTimeMovie; 
 _assetExport.outputURL =outputFileUrl; 
 _assetExport.shouldOptimizeForNetworkUse=YES; 
 self.theEndVideoURL=outputFileUrl; 

 [_assetExportexportAsynchronouslyWithCompletionHandler: 
 ^(void ) { 
  [MBProgressHUDhideHUDForView:self.viewanimated:YES]; 
  // Play  
  NSURL*url = [NSURLfileURLWithPath:outputFilePath]; 
  MPMoviePlayerViewController *theMovie =[[MPMoviePlayerViewControlleralloc]initWithContentURL:url]; 
  [selfpresentMoviePlayerViewControllerAnimated:theMovie]; 
  theMovie.moviePlayer.movieSourceType=MPMovieSourceTypeFile; 
  [theMovie.moviePlayerplay]; 
 } 
 ]; 
 NSLog(@" Done! Output path ==%@",outputFilePath); 
} 

// Create and add audio material through file paths  
- (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); 

 // Set the volume  
 //AVMutableAudioMixInputParameters (Audio Mix with Variable Input Parameters)  
 //audioMixInputParametersWithTrack (Audio Mix Input Parameters and Tracks)  
 AVMutableAudioMixInputParameters *trackMix =[AVMutableAudioMixInputParametersaudioMixInputParametersWithTrack:track]; 
 [trackMixsetVolume:0.8fatTime:startTime]; 

 // Add material to array  
 [audioMixParamsaddObject:trackMix]; 

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

 #pragma mark -  Save path  
-(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; 
} 

Related articles: