-->

how to convert nsdata to MPMediaitem song iOS Sdk

2020-04-18 07:01发布

问题:

i converted MPMediaItem to NSData and stored that in database, now i have to convert that NSData to MPMediaItem to play that song in mediaplayer. Used below code to convert MPMediaItem to NSData:

NSURL *url = [song valueForProperty: MPMediaItemPropertyAssetURL];

AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];

AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset
                                                                  presetName: AVAssetExportPresetPassthrough];

exporter.outputFileType = @"public.mpeg-4";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *exportFile = [documentsDirectory stringByAppendingPathComponent:           
                        @"exported.mp4"];

NSURL *exportURL = [[NSURL fileURLWithPath:exportFile] retain];
exporter.outputURL = exportURL; 

// do the export
// (completion handler block omitted) 
[exporter exportAsynchronouslyWithCompletionHandler:
 ^{
     NSData *data = [NSData dataWithContentsOfFile: [documentsDirectory 
                                                     stringByAppendingPathComponent: @"exported.mp4"]];


 }];

can anyone please tell me how to convert NSData to MPMediaItem.

回答1:

You can't. An MPMediaItem represents an item in the iPod library but third-party apps cannot add anything to that library.

You could however write your NSData object to a file and then use its URL with either AVPlayerItem/AVPlayer or MPMoviePlayerController (don't be fooled by the name, it can also play audio-only files).