0

If you use [MPMediaQuery genresQuery] then you get MPMediaItemCollection which doesn't hold the total play time. You can use the representativeItem but this one gives you only that particular item play time.

Is there an efficient way how to display all albums including the total play time?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
PerfectGamesOnline.com
  • 1,774
  • 1
  • 18
  • 31

1 Answers1

0

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
            }
        }
    }
Pavel
  • 61
  • 7