Home > Back-end >  MPMediaPropertyPredicate - filter MPMediaQuery by songs duration
MPMediaPropertyPredicate - filter MPMediaQuery by songs duration

Time:04-09

I am fetching music tracks from user's music library like this:

    let query = MPMediaQuery.songs()
    let predicate = MPMediaPropertyPredicate(value: false, forProperty: MPMediaItemPropertyIsCloudItem)
    
    query.addFilterPredicate(predicate)
    
    if let fetchedSongs = query.items {
       // Do something with tracks
    }

However, I don't need songs longer than 5 minutes. I tried to add a new predicate MPMediaPropertyPredicate to filter out all tracks longer than 5 minutes but with no success - I am not sure what to use in the value parameter and if I can use a condition like "duration < 300" in a simple NSPredicate.

CodePudding user response:

Just do the query and filter the results yourself. Here's code from my own app that gets all the very short songs:

let query = MPMediaQuery.songs()
// always need to filter out songs that aren't present
let isPresent = MPMediaPropertyPredicate(value:false,
                                         forProperty:MPMediaItemPropertyIsCloudItem,
                                         comparisonType:.equalTo)
query.addFilterPredicate(isPresent)
guard let items = query.items else {return} //

let shorties = items.filter { //
    let dur = $0.playbackDuration
    return dur < 30
}
  • Related