Search code examples
iosmpmediaplayercontroller

Play specific song


I am looking at ways to store song information and then play a specific song. I've seen this post: How do you use MPMediaItemPropertyPersistentID to play music in iPhone Music Player Framework?

If I have a MPMediaItemPropertyPersistentID already, can I directly play that song without looping every single song until I find a matching id?


Solution

  • You don't have to do this by looping through all the items in the library. It can be done via MPMediaQuery, something like this:

    NSNumber *persistentIDNumber = [NSNumber numberWithInteger:4238475234];
    
    MPMusicPlayerController *player = [MPMusicPlayerController applicationMusicPlayer];
    
    MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:persistentIDNumber forProperty:MPMediaEntityPropertyPersistentID];
    
    MPMediaQuery *query = [[MPMediaQuery alloc] init];
    
    [query addFilterPredicate: predicate];
    
    [player setQueueWithQuery:query];
    [player prepareToPlay];
    [player play];