我正在制作一款音乐应用程序,用户可以访问iOS音乐库,并将歌曲保存到其应用程序中(即文档目录)。我可以使用MPMediaPickerController访问音乐库,但不知道如何处理其委托方法,以便将所选歌曲保存到我的文档目录中。 目前我正在使用以下代码
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker
didPickMediaItems: (MPMediaItemCollection *) collection
{
[self dismissViewControllerAnimated:YES completion:nil];
[self playSelectedMediaCollection: collection];
}
- (void) playSelectedMediaCollection: (MPMediaItemCollection *) collection {
if (collection.count == 1) {
NSArray *items = collection.items;
MPMediaItem *mediaItem = [items objectAtIndex:0];
[self mediaItemToData:mediaItem];
}
}
-(void)mediaItemToData:(MPMediaItem*)mediaItem
{
// Implement in your project the media item picker
MPMediaItem *curItem = mediaItem;//musicPlayer.nowPlayingItem;
NSURL *url = [curItem valueForProperty: MPMediaItemPropertyAssetURL];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset
presetName: AVAssetExportPresetPassthrough];
exporter.outputFileType = @"public.mpeg-4";
NSString *exportFile = [[self myDocumentsDirectory] stringByAppendingPathComponent:
@"exported.mp4"];
NSURL *exportURL = [NSURL fileURLWithPath:exportFile] ;
exporter.outputURL = exportURL;
NSData *data = [NSData dataWithContentsOfFile: [[self myDocumentsDirectory]
stringByAppendingPathComponent: @"exported.mp4"]];
//
// NSLog(@"%@",data);
// NSURL *audioUrl = exportURL;
// NSLog(@"Audio Url=%@",audioUrl);
// audioData = [NSData dataWithContentsOfURL:audioUrl];
// NSLog(@"%@",audioData);
// Do with data something
// do the export
// (completion handler block omitted)
[exporter exportAsynchronouslyWithCompletionHandler:
^{
// int exportStatus=exporter.status;
NSLog(@"%d export status",exporter.status);
if (exporter.status==AVAssetExportSessionStatusCompleted)
{
NSLog(@"successfull");
}
NSData *data = [NSData dataWithContentsOfFile: [[self myDocumentsDirectory]
stringByAppendingPathComponent: @"exported.mp4"]];
NSURL *audioUrl = exportURL;
NSLog(@"Audio Url=%@",audioUrl);
audioData = [NSData dataWithContentsOfURL:audioUrl];
NSLog(@"%@",audioData);
// Do with data something
}];
}
在上面的代码中,调试器从未进入导出会话异步块。如果您有任何适用于我的要求的工作代码,或者是否需要对上述代码进行任何修改,请告诉我。 提前致谢…