title: iPhone: NSData representation of Audio file for Editing
body: <p>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.</p>
  
  <p>For this I have written following code. I got this idea from <a href="https://stackoverflow.com/questions/2399498/objective-c-how-to-serialize-audio-file-into-small-packets-that-can-be-played">here</a>.</p>
  
  <pre><code>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];
  </code></pre>
  
  <p>Using following code to play converted sound file:</p>
  
  <pre><code>AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] 
                            initWithContentsOfURL:[NSURL URLWithString:[self filePath:@"converted.caf"]]  error:nil];
  [audioPlayer prepareToPlay];
  [audioPlayerr play];
  </code></pre>
  
  <p>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.</p>
  
  <p>Thanks.</p>