Topics

#105: Media Library Basics 🎵

Topics

The Media Player Framework is how we can interact with the media library on a user's device. Today we'll look at the basics and build a fun little personal-use app to play some of our own favorite albums. Let's get started.

We'll start with a simple UICollectionViewController. It'll have a flow layout and we'll size the items so they make 2 equal columns:

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()
  guard let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout else { return }

  squareSize = view.bounds.size.width / 2.0
  flowLayout.itemSize = CGSizeMake(squareSize, squareSize)
}

In viewWillAppear we'll retrieve the albums we want to display.

We'll use the Async library (Bite #35) to make hopping queues easier:

Async.background {
  self.albums = (MPMediaQuery.albumsQuery().collections ?? [])
}.main { self.collectionView?.reloadData() }

When dequeuing cells, we grab the artwork from the representative item of each album. We use our squareSize so it displays nice and crisp:

let album = albums[indexPath.item]
let item = album.representativeItem!
let artwork = item.valueForProperty(MPMediaItemPropertyArtwork) as! MPMediaItemArtwork
cell.imageView.image = artwork.imageWithSize(CGSizeMake(squareSize, squareSize))

Now we'll personalize our app. We'll add a filter to our MPMediaQuery so it only returns some of the albums in our library:

query.addFilterPredicate(
  MPMediaPropertyPredicate(
    value: "Bad Religion",
    forProperty: MPMediaItemPropertyArtist,
    comparisonType: .Contains
  )
)

Finally, when the user selects a cell, we'll grab the system's music player and play the selected album:

We chose to filter to just a single artist here, but MPMediaPredicate is quite powerful. We can supply multiple filters, tons of properties, etc.

let album = albums[indexPath.item]

let player = MPMusicPlayerController.systemMusicPlayer()
player.setQueueWithItemCollection(album)
player.play()

Success!

This is just the beginning of what's possible with the Media Player Framework. Be sure to download the project at j.mp/bite105 and try it for yourself!