Search code examples
objective-citunes

How to get only songs from itunes library with itlibrary.h


This is the way the docs say to get all media items from library, however I want to get only the songs.

#import <iTunesLibrary/ITLibrary.h>

ITLibrary *library = [ITLibrary libraryWithAPIVersion:@"1.0" error:&error];
if (library)
{
    tracks = library.allMediaItems; //  <- NSArray of ITLibMediaItem
}

I found this answer: How to get all tracks from an album using iTunes.h/Scripting Bridge

I'm not sure how to adapt it to do what I need it to, or maybe it is less complicated now?


Solution

  • tracks = library.allMediaItems; is a NSArray of ITLibMediaItem objects.

    According to the doc, it as a property mediaKind that gives it the item is a song (ITLib​Media​Item​Media​Kind​Song) or another kind of media.

    So, you just have to use the predicate:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"mediaKind == %d", ITLib​Media​Item​Media​Kind​Song]]
    

    So to filter (with previous predicate)

    tracks = [library.allMediaItems filteredArrayUsingPredicate:predicate];