Displaying song metadata

Most .mp3 files contain metadata in the form of ID3 tags. These metadata tags are used by applications such as iTunes to extract information about a song and display it to the user, as well as to categorize a music library or filter it. You can gain access to an audio file's metadata through code, by loading the audio file into an AVPlayerItem object and extracting the metadata for its internal AVAsset instance. An AVAsset object contains information about a media item, such as its type, location, and more. When you load a file using an AVPlayerItem object, it will automatically create a corresponding AVAsset object for you.

A single asset can contain loads of metadata in the metadata dictionary. Luckily, Apple has captured all of the valid ID3 metadata tags in the AVMetadataIdentifier object, so once you have extracted the metadata for an AVAsset, you can loop over all of its metadata to filter out the data you need. The following method does this, and sets the extracted values on the titleLabel variable of AudioViewController, as shown here:

func showMetadataForURL(_ url: URL) {
  let mediaItem = AVPlayerItem(url: url)
  let metadata = mediaItem.asset.metadata
  var information = [String]()

  for item in metadata {
    guard let identifier = item.identifier
      else { continue }

    switch identifier {
    case .id3MetadataTitleDescription, .id3MetadataBand:
      information.append(item.value?.description ?? "")
    default:
      break
    }
  }

  let trackTitle = information.joined(separator: " - ")
  titleLabel.text = trackTitle
}

Make sure to add a call to this method from loadTrack(), and pass the audio file's URL that you obtain in loadTrack() to showMetadataForURL(_:). If you run your app now, your basic functionality should be all there. The metadata should be shown correctly, the scrubber should work, and you should be able to skip songs or pause the playback.

Even though your media player seems to be pretty much done at this point, did you notice that the music pauses when you send the app to the background? To make your app feel more like a real audio player, you should implement background audio playback and make sure the currently playing song is presented on the user's lock screen, similar to how the native music app for iOS works. This is precisely the functionality you will add next.