If you need to get playback time for the whole library then you just need to iterate through items in MPMediaQuery
.
let query = MPMediaQuery.albums()
let items = query.items
var totalTime: TimeInterval = 0.0
if items != nil {
for item in items! {
totalTime += item.playbackDuration
}
}
let duration = Int(totalTime)
let seconds = duration % 60
let minutes = duration / 60 % 60
let hours = duration / 3600
print("Total playback time: \(hours):\(minutes):\(seconds)")
Collections will give you an arrays of MPMediaItems
sorted alphabetically and grouped in collections by groupingType
options (artists, albums, genres, etc.). If you need for example playback time for every album in library then you can iterate like this:
let query = MPMediaQuery.albums()
let collections = query.collections
var albumTime: TimeInterval = 0.0
if collections != nil {
for collection in collections! {
if let albumTitle = collection.representativeItem?.value(forProperty: MPMediaItemPropertyAlbumTitle) {
for item in collection.items {
albumTime += item.playbackDuration
}
let duration = Int(albumTime)
let seconds = duration % 60
let minutes = duration / 60 % 60
let hours = duration / 3600
print("\"\(albumTitle)\" playback time: \(hours):\(minutes):\(seconds)")
albumTime = 0.0
}
}
}