The following code will read the ipod library song from its url and copy it to disk for use..
note this code wont work with m4as because the URLs from ipod library for m4as dont contains headers, for that you will need to use AVAssetExporter to write the header and music data to disk.
-(void)exportMP3:(NSURL*)url toFileUrl:(NSString*)fileURL
{
AVURLAsset *asset=[[[AVURLAsset alloc] initWithURL:url options:nil] autorelease];
AVAssetReader *reader=[[[AVAssetReader alloc] initWithAsset:asset error:nil] autorelease];
NSMutableArray *myOutputs =[[[NSMutableArray alloc] init] autorelease];
for(id track in [asset tracks])
{
AVAssetReaderTrackOutput *output=[AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:track outputSettings:nil];
[myOutputs addObject:output];
[reader addOutput:output];
}
[reader startReading];
NSFileHandle *fileHandle ;
NSFileManager *fm=[NSFileManager defaultManager];
if(![fm fileExistsAtPath:fileURL])
{
[fm createFileAtPath:fileURL contents:[[[NSData alloc] init] autorelease] attributes:nil];
}
fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:fileURL];
[fileHandle seekToEndOfFile];
AVAssetReaderOutput *output=[myOutputs objectAtIndex:0];
int totalBuff=0;
while(TRUE)
{
CMSampleBufferRef ref=[output copyNextSampleBuffer];
if(ref==NULL)
break;
//copy data to file
//read next one
AudioBufferList audioBufferList;
NSMutableData *data=[[NSMutableData alloc] init];
CMBlockBufferRef blockBuffer;
CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(ref, NULL, &audioBufferList, sizeof(audioBufferList), NULL, NULL, 0, &blockBuffer);
for( int y=0; y<audioBufferList.mNumberBuffers; y++ )
{
AudioBuffer audioBuffer = audioBufferList.mBuffers[y];
Float32 *frame = audioBuffer.mData;
// Float32 currentSample = frame[i];
[data appendBytes:frame length:audioBuffer.mDataByteSize];
// written= fwrite(frame, sizeof(Float32), audioBuffer.mDataByteSize, f);
////NSLog(@"Wrote %d", written);
}
totalBuff++;
CFRelease(blockBuffer);
CFRelease(ref);
[fileHandle writeData:data];
// //NSLog(@"writting %d frame for amounts of buffers %d ", data.length, audioBufferList.mNumberBuffers);
[data release];
}
// //NSLog(@"total buffs %d", totalBuff);
// fclose(f);
[fileHandle closeFile];
}