从iOS音乐库中将歌曲保存到文档目录

4

我正在制作一款音乐应用程序,用户可以访问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

     }];
}

在上面的代码中,调试器从未进入导出会话异步块。如果您有任何适用于我的要求的工作代码,或者是否需要对上述代码进行任何修改,请告诉我。 提前致谢…
2个回答

2

我认为有遗漏

/

尝试这段代码

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


仍然无法调试块[exporter exportAsynchronouslyWithCompletionHandler:]我想首先知道为什么我的编译器没有进入这个块,以及为什么我无法获取我的导出状态。 - Rahul Mathur
该块正在被调用,但每次我的导出状态都是4,即失败。我不知道我漏掉了什么。 - Rahul Mathur
你问关于带有导出会话的工作代码……你试过这个例子了吗? - andproff
导出会话支持 MP3 文件吗? - Rahul Mathur
@RahulMathur 是的,它支持。请查看此文档:https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVFoundation_Constants/Reference/reference.html#//apple_ref/doc/uid/TP40009539 - Tirth

1

适用于 Swift 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")
            }

        })

    }

}

嗨!也许你知道如何将文件导出为音乐库中的格式?不需要转换为m4a或其他格式。 - VyacheslavBakinkskiy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接