如何将iPod库中的歌曲复制到应用程序并使用AVAudioPlayer播放?

虽然重复,但我想播放使用AVAudioPlayer从iPod库的歌曲。 那么复制iPod库歌曲之后是否可以复制到应用程序?

我有一个代码,将歌曲转换为caf格式,然后我可以使用AVAudioPlayer播放。 但转换时间太长。 那么还有其他方法可以做到吗?

下面的代码将从它的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]; } 

您可以使用MPMusicPlayerController,它是为了在应用程序中包含iPod接口而构build的。 请参阅文档: http : //developer.apple.com/library/ios/#documentation/mediaplayer/reference/MPMusicPlayerController_ClassReference/Reference/Reference.html 。

如果你真的需要使用MPMediaPickerController(这是我假设你正在使用从用户库中select歌曲),请参阅这篇文章如何播放歌曲: 使用MPMediaItems与AVAudioPlayer