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.