1

我正在製作一個音樂應用程序,用戶可以在其中訪問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 

    }]; 
} 

在上面的代碼,調試器從來沒有涉及到出口會話異步塊。讓我知道是否有任何修改需要在上面的代碼,或者如果你有任何工作代碼可用於我的要求。 在此先感謝....

回答

1

我認爲被遺漏

/

試試這個代碼

NSString *exportFile = [[self myDocumentsDirectory] stringByAppendingPathComponent: @"/exported.mp4"];

修訂

或原因可能是presetName哪些你使用

/*這個出口選項將導致所有軌道的媒體,通過對完全一樣存儲在源資產的輸出被傳遞,除了 軌道針對直通是不可能的,因爲限制的通常容器格式,如指定的outputFileType所示。 此選項不包含在由-allExportPresets和-exportPresetsCompatibleWithAsset返回的數組中。 */ AVF_EXPORT NSString * const AVAssetExportPresetPassthrough NS_AVAILABLE(10_7,4_0);

這裏是關於exportAsynchronouslyWithCompletionHandler很好的說明:https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AV‌​AssetExportSession_Class/Reference/Reference.html

+0

仍然無法調試塊[出口exportAsynchronouslyWithCompletionHandler: 我只是想先知道,爲什麼我的編譯器dosent去這個塊,爲什麼我無法得到我的出口狀態 –

+0

塊被調用,但每次我的出口狀態是4即失敗。我不知道我錯過了什麼。 –

+0

你問出口會話的工作代碼......你試過[這個例子](https://developer.apple.com/library/mac/samplecode/avexporter/Introduction/Intro.html)? – proff

0

的雨燕3.0或4

func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) { 
    mediaPicker.dismiss(animated: true) { 

     print("You selected \(mediaItemCollection)") 

     let item: MPMediaItem = mediaItemCollection.items[0] 
     let pathURL: URL? = item.value(forProperty: MPMediaItemPropertyAssetURL) as? URL 
     if pathURL == nil { 
      print("Picking Error") 
      return 
     } 

     // get file extension andmime type 
     let str = pathURL!.absoluteString 
     let str2 = str.replacingOccurrences(of : "ipod-library://item/item", with: "") 
     let arr = str2.components(separatedBy: "?") 
     var mimeType = arr[0] 
     mimeType = mimeType.replacingOccurrences(of : ".", with: "") 

     // Export the ipod library as .m4a file to local directory for remote upload 
     let exportSession = AVAssetExportSession(asset: AVAsset(url: pathURL!), presetName: AVAssetExportPresetAppleM4A) 
     exportSession?.shouldOptimizeForNetworkUse = true 
     exportSession?.outputFileType = AVFileTypeAppleM4A 

     let documentURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) 
     let outputURL = documentURL.appendingPathComponent("custom.m4a") 

     //Delete Existing file 
     do { 
      try FileManager.default.removeItem(at: outputURL) 
     } catch let error as NSError { 
      print(error.debugDescription) 
     } 

     exportSession?.outputURL = outputURL 
     exportSession?.exportAsynchronously(completionHandler: {() -> Void in 

      if exportSession!.status == AVAssetExportSessionStatus.completed { 
       print("Export Successfull") 
      } 

     }) 

    } 

} 
相關問題