How to play a song from the itunes library in iphone

user169964 picture user169964 · Nov 3, 2009 · Viewed 8.3k times · Source

Hi i need to play a song from the itunes library. I had gone through the Apples ipod Library Access Guide and got the code.

MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSLog(@"Logging items from a generic query...");
NSArray *itemsFromGenericQuery = [everything items];
MPMediaItem *song;
for (song in itemsFromGenericQuery) 
{
    NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
    NSLog (@"%@", songTitle);
}

//assign a playback queue containing all media items on the device
[myPlayer setQueueWithQuery:everything];//setQueueWithQuery:everything];

//start playing from the begining
[myPlayer play];

But This will start playing from the very beginning of the library list. I need to play a song when i select it from the list. Can anyone help me please...

Thanks, Shibin.

Answer

Vaishnavi Naidu picture Vaishnavi Naidu · Nov 3, 2009

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]; 
}