虽然重复,但我想从iPod库使用AVAudioPlayer
播放歌曲。那么将iPod Library歌曲复制到应用程序后是否可以复制它?
我有一个代码可以将歌曲转换为caf格式,然后我可以使用AVAudioPlayer
播放。但转换需要很长时间。那么我还能采取其他任何方式吗?
答案 0 :(得分:6)
以下代码将从其url中读取ipod库歌曲并将其复制到磁盘以供使用。 请注意,此代码不适用于m4as,因为来自ipod库的m4as的URL不包含标头,因此您需要使用AVAssetExporter将标头和音乐数据写入磁盘。
-(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];
}
答案 1 :(得分:-1)
您可以使用MPMusicPlayerController,它是为在应用程序中包含iPod接口而构建的。请参阅文档:http://developer.apple.com/library/ios/#documentation/mediaplayer/reference/MPMusicPlayerController_ClassReference/Reference/Reference.html。
如果你真的需要使用MPMediaPickerController(我假设你用它来选择用户库中的歌曲),请参阅这篇文章,了解如何播放歌曲: Using MPMediaItems with AVAudioPlayer