I have been scratching my head since long now but not getting around to this. I haven't found a single example for Audio editing! I want to insert new Audio file in between somewhere in original Audio file, save it as new converted audio files.
For this I have written following code. I got this idea from here.
NSString *file1 = [[NSBundle mainBundle] pathForResource:@"file1" ofType:@"caf"]; // Using PCM format
NSString *file2 = [[NSBundle mainBundle] pathForResource:@"file2" ofType:@"caf"];
NSData *file1Data = [[NSData alloc] initWithContentsOfFile:file1];
NSData *file2Data = [[NSData alloc] initWithContentsOfFile:file2];
NSMutableData *mergedData =[[NSMutableData alloc] initWithCapacity:([file1Data length] + [file2Data length])];
// First chunk from original sound file
NSRange firstChunk;
firstChunk.length = startingPosition;
firstChunk.location = 0;
[mergedData appendData:[file1Data subdataWithRange:firstChunk]];
// Add new sound
[mergedData appendData:file2Data];
// First chunk from original sound file
NSRange secondChunk;
secondChunk.length = [file1Data length] - startingPosition;
secondChunk.location = startingPosition;
[mergedData appendData:[file1Data subdataWithRange:secondChunk]];
NSLog(@"File1: %d, File2: %d, Merged: %d", [file2Data length], [file2Data length], [mergedData length]);
// Convert mergedData to Audio file
[mergedData writeToFile:[self filePath:@"converted.caf"] atomically:YES];
[file1Data release];
[file2Data release];
[mergedData release];
Using following code to play converted sound file:
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:[NSURL URLWithString:[self filePath:@"converted.caf"]] error:nil];
[audioPlayer prepareToPlay];
[audioPlayerr play];
The converted file doesn't play. Further researching on this I found that converting sound to NSData truncates sound header/footer. Is that right? Could anyone please help me to get this sorted out please.
Thanks.
I think your best bet would be to use an ExtAudioFileRef to extract the audio samples of each file into buffers.
Then you can freely mix the samples together to and from whatever position you like and save the new mixed file to disk using ExtAudioFileWriteAsync.
For example: Extract sound 1 into buffer A. Extract sound 2 into buffer B.
Create buffer C whose size is A's length plus B's length. Then write that buffer to disk in whatever format you want using ExtAudioFileWriteAsync.
That file should then be playable by AVAudioPlayer.