我正在製作一個音樂應用程序,用戶可以在其中訪問ios音樂庫,並可以將歌曲保存到其應用程序(即文檔目錄)。我能夠使用MPMediaPickerController訪問音樂庫,但不知道如何處理其委託方法,以便將選定的歌曲保存到我的文檔目錄中。 目前我使用此代碼從ios音樂庫保存歌曲到文檔目錄
- (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
}];
}
在上面的代碼,調試器從來沒有涉及到出口會話異步塊。讓我知道是否有任何修改需要在上面的代碼,或者如果你有任何工作代碼可用於我的要求。 在此先感謝....
仍然無法調試塊[出口exportAsynchronouslyWithCompletionHandler: 我只是想先知道,爲什麼我的編譯器dosent去這個塊,爲什麼我無法得到我的出口狀態 –
塊被調用,但每次我的出口狀態是4即失敗。我不知道我錯過了什麼。 –
你問出口會話的工作代碼......你試過[這個例子](https://developer.apple.com/library/mac/samplecode/avexporter/Introduction/Intro.html)? – proff