How to play a song from the itunes library in iphone
Solution 1:
Using the MPMediaPickerController
instance you can choose from the iPod library's song list, album list, etc.. Here is an example which selects all the songs from the iPod and displays in a modal view controller.
- (IBAction) selectSong: (id) sender
{
MPMediaPickerController *picker =
[[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker.delegate = self;
picker.allowsPickingMultipleItems = NO;
picker.prompt = NSLocalizedString (@"Select any song from the list", @"Prompt to user to choose some songs to play");
[self presentModalViewController: picker animated: YES];
[picker release];
}
Now you need to implement the delegate to store the song into your local variable. Here, selectedSongCollection
is an instance of MPMediaItemCollection
.
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection
{
[self dismissModalViewControllerAnimated: YES];
selectedSongCollection=mediaItemCollection;
}
After you are done with selecting the song, implement the delegate to dismiss the picker:
- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker
{
[self dismissModalViewControllerAnimated: YES];
}
Solution 2:
You are assigning a playlist of all songs to the music player, so of course it is going to play the entire list, starting at the beginning. If you want the user to select a specific song from the iPod library, use MPMediaPickerController
.
Solution 3:
I couldn't use theMPMediaPickerController
in my scenario.
My short answer to question is to have a look at [musicplayer setNowPlayingItem:item]
here's some code below from my implementation.
// Create a new query
MPMediaQuery *query = [MPMediaQuery songsQuery];
MPMediaPropertyPredicate *mpp = [MPMediaPropertyPredicate predicateWithValue:@"a" forProperty:MPMediaItemPropertyTitle comparisonType:MPMediaPredicateComparisonContains];
[query addFilterPredicate:mpp];
// Retrieve the results and reload the table data
DATAENV.songCollections = [NSMutableArray arrayWithArray:query.collections];
//populate cell rows with
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MPMediaItem *item = [[[DATAENV.songCollections objectAtIndex:indexPath.row] items] lastObject];
titleLbl = [item valueForProperty:MPMediaItemPropertyTitle];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
MPMediaItem *item = [[[self.songCollections objectAtIndex:indexPath.row] items] lastObject];
[PLAYER setNowPlayingItem:item];
[PLAYER play];
}
Where PLAYER/ DATAENV are my singletons
#define PLAYER [[AudioController sharedAudioController_instance] musicPlayer]
#define DATAENV [DataEnvironment sharedDataEnvironment_instance]