Combine two audio files into one in the lens c

Possible duplicate:
merge audio files on iPhone

I am trying to merge 2 audio files into one file. For example: file1.mp3 - it says "I am." file2.mp3 - this says "George". I want to get the combined file3.mp3 file that says "I'm George."

How to do this in objective-C?

+2
source share
3 answers

Look at the structure of AVFoundation ... There are many ways, but the simplest one for you might be ...

  • create AVAsset for both files (use subclass of AVURLAsset)
  • alloc AVMutableComposition (composition),
  • add AVMutableCompositionTrack with type AVMediaTypeAudio to composition

[composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

  • get the track from the first AVAsset and add it to AVMutableCompositionTrack,
  • get the track from the second AVAsset and add it to the AVMutableCompositionTrack,
  • then create an AVAssetExportSession with your composition and export it.

A simplified description, but you will get a hint. Depends on how many tracks you have, what effects you want to use, etc.

If you really want to see some real code, open the AVMovieExporter example, copy this code and delete the video materials and leave only audio there.

+11
source

You can combine 2 mp3 files as: -

  NSMutableData *part1 = [NSMutableData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"file1" ofType: @"mp3"]]; NSMutableData *part2 = [NSMutableData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"file2" ofType: @"mp3"]]; [part1 appendData: part2]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [paths objectAtIndex:0]; NSString *myMp3 = [documentsDir stringByAppendingPathComponent: @"final.mp3"]; [part1 writeToFile:myMp3 atomically:YES]; 

This way you can directly add the file to the file. I used it in one of my applications. This is a bit complicated for other formats where you need to update the file header accordingly, but relatively easier with mp3.

UPDATE:

Well, you should also make sure that the bit rates of the mp3 files you are trying to combine are the same. If they are different, they will merge, but they will play only partially or, possibly, at all. Therefore, make sure that the bit-bit is synchronized with each other.

+1
source

One alternative is to use AVAssetReader to convert all mp3 files to uncompressed audio files or even memory buffers if the sound is short enough. Uncompressed PCM data can simply be merged, mixed, or crossed out as needed. Then use AVAssetWriter to write the result to a compressed file format (such as aac), if necessary.

0
source

All Articles