Extracting MP3 Metadata using Swift and AVFoundation

AutoMagicianAE
2 min readApr 2, 2023

--

MP3 files can contain metadata that provides valuable information about the audio content, such as the song title, artist name, album name, and more. This metadata is stored within the file, separate from the audio data, and can be accessed programmatically using various tools and libraries.

In this post, we will explore how to extract MP3 metadata using Swift and the AVFoundation framework. AVFoundation is a robust multimedia framework provided by Apple, which includes classes for working with audio, video, and other types of media.

First, let’s consider a simple example of how to extract the title and artist name from an MP3 file:

import AVFoundation

let asset = AVAsset(url: URL(fileURLWithPath: "/path/to/mp3/file.mp3"))
let metadata = asset.commonMetadata

for item in metadata {
if let value = item.value {
switch item.commonKey?.rawValue {
case "title":
print("Title: \(value)")
case "artist":
print("Artist: \(value)")
default:
break
}
}
}

In this example, we create an AVAsset object using the URL of the MP3 file we want to extract metadata. We then use the commonMetadata property of the asset to access the metadata associated with the file.

The commonMetadata property returns an array of AVMetadataItem objects representing individual metadata items. We loop through the array using a for loop and check each item’s commonKey property value to determine its type.

If the commonKey property matches a particular field we are interested in (in this case, the title and artist fields), we print out the corresponding value using the value property of the item.

Note that the value property is optional since not all metadata items may have a value. In our example, we use optional binding (if let value = item.value) to safely unwrap the optional value before using it.

Now, let’s take a look at a list of common types of information that can be stored in MP3 metadata:

  1. Song title
  2. Artist name
  3. Album name
  4. Track number
  5. Genre
  6. Year of release
  7. Composer
  8. Performer
  9. Album artist
  10. Lyrics
  11. Comments
  12. Rating
  13. Duration
  14. Bitrate
  15. Sample rate
  16. Channels
  17. Encoder
  18. Original artist
  19. Original album
  20. Disc number
  21. BPM (beats per minute)
  22. ISRC (International Standard Recording Code)
  23. Catalog number
  24. UPC (Universal Product Code)
  25. Cover art or album artwork

Note that not all of these fields are required or present in every MP3 file, and there may be additional fields depending on the metadata format and the software used to create or edit the file.

In conclusion, extracting MP3 metadata using Swift and AVFoundation is a straightforward process that can provide valuable information about audio content. By leveraging the power of AVFoundation, developers can easily incorporate metadata extraction functionality into their apps and workflows.

--

--