Like UIImagePickerView to pick image from image gallery we can also pick up any music file from the music gallery of the device and can use it in our application with the help of MPMediaPickerController.
For that you need to add AVFoundation framework in your application. also to play the picked file we need to add MediaPlayer framework. and to use them just import them in respective view controller. Also in .h file you have to add MPMediaPickerControllerDelegate.
In button click action write the following
MPMediaPickerController *picker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker.delegate = self;
picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController: picker animated: YES];This will present a controller from where we will be able to access the device’s music library. Also to get the picked file override the delegate method
– (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection {
// Dismiss the media item picker.
[self dismissModalViewControllerAnimated: YES];MPMediaItem *item = [[mediaItemCollection items] objectAtIndex:0];
NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
[self dismissModalViewControllerAnimated: YES];// Play the item using MPMusicPlayer
MPMusicPlayerController* appMusicPlayer = [MPMusicPlayerController applicationMusicPlayer];
[appMusicPlayer setQueueWithItemCollection:mediaItemCollection]; [appMusicPlayer play];AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:url];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[player play];}
Done. Now you can play any music file from device music library into your application.
Happy Coding…..!