1

I am using MPMediaPickerController to upload music files. When I tried to convert MPMediaItem to NSData, the NSData always returns NULL. Here is my code:

- (IBAction)addMusic:(id)sender {
      MPMediaPickerController *soundPicker=[[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
      soundPicker.delegate=self;
      soundPicker.allowsPickingMultipleItems=NO;
      [self presentViewController:soundPicker animated:YES completion:nil];
}
- (void)mediaPicker: (MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{
      MPMediaItem *item = [[mediaItemCollection items] objectAtIndex:0];
      NSURL *url = [item valueForProperty: MPMediaItemPropertyAssetURL];
      NSString *audioFilePath = [NSString stringWithFormat:@"%@",url];   
      NSData *audioData = [NSData dataWithContentsOfFile:audioFilePath];
      [self dismissViewControllerAnimated:YES completion:nil];
}

Please suggest what can I do to convert MPMediaItem to NSData.

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
Nishi Bansal
  • 315
  • 1
  • 5
  • 16

1 Answers1

0

Your problem is in these three lines:

NSURL *url = [item valueForProperty: MPMediaItemPropertyAssetURL];
NSString *audioFilePath = [NSString stringWithFormat:@"%@",url];   
NSData *audioData = [NSData dataWithContentsOfFile:audioFilePath];

Try doing:

NSURL *url = [item valueForProperty: MPMediaItemPropertyAssetURL];
NSError *error = nil;
NSData *audioData = [NSData dataWithContentsOfURL:url options:nil error:&error];
if(!audioData)
    NSLog(@"error while reading from %@ - %@", [url absoluteString], [error localizedDescription]);

And see if that works better.

If you're interested, what was wrong with the first block of code there was that [NSString stringWithFormat:@"%@",url] probably gives a nil result, since url is a NSURL object and NSString's format is expecting a NSString object.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215