Book

Exploring MusicKit and Apple Music API

Unlock the full power of MusicKit & Apple Music APIs in your apps with the best guide! Use code musickit-blog for a limited-time 35% discount!

MusicKit got more powerful when it added the library capabilities in iOS 16. One of the highlights was the MusicLibrary class and the method to add a song to a playlist. This post explores how to use MusicKit to add songs to a playlist, including the MusicPlaylistAddable protocol, the MusicLibrary class, and the add method. It also discusses the limitation of adding one song at a time and how to overcome it by adding multiple songs using a loop.

MusicPlaylistAddable Protocol

To add songs to a playlist, the music item needs to conform to the MusicPlaylistAddable protocol.

/// A protocol for music items that your app can add to the music library.
@available(iOS 16.0, tvOS 16.0, watchOS 9.0, *)
@available(macOS, unavailable)
@available(macCatalyst, unavailable)
public protocol MusicLibraryAddable: MusicItem {
}

Both Song and Track structure conform to this protocol.

@available(iOS 16.0, tvOS 16.0, watchOS 9.0, *)
@available(macOS, unavailable)
@available(macCatalyst, unavailable)
extension Song: MusicLibraryAddable, MusicPlaylistAddable {
}

@available(iOS 16.0, tvOS 16.0, watchOS 9.0, *)
@available(macOS, unavailable)
@available(macCatalyst, unavailable)
extension Track: MusicLibraryAddable, MusicPlaylistAddable {
}

@available(iOS 16.0, tvOS 16.0, watchOS 9.0, *)
@available(macOS, unavailable)
@available(macCatalyst, unavailable)
extension Playlist.Entry: MusicLibraryAddable, MusicPlaylistAddable {
}

MusicLibrary Class

The MusicLibrary class allows your app to access the user’s music library.

/// An object your app uses to access the user’s music library.
@available(iOS 16.0, tvOS 16.0, watchOS 9.0, macOS 14.0, macCatalyst 17.0, *)
public class MusicLibrary {

    /// A shared object that allows your app to modify the user’s music library.
    public static let shared: MusicLibrary
}

It provides various methods to interact with the music library, including adding items to a playlist. The add method of the MusicLibrary class is used to add an item to the end of an existing playlist.

/// Adds an item to the end of an existing playlist.
///
/// - Returns: The updated playlist.
@available(macOS, unavailable)
@available(macCatalyst, unavailable)
@discardableResult
public func add<MusicItemType>(_ item: MusicItemType, to playlist: Playlist) async throws -> Playlist where MusicItemType: MusicPlaylistAddable

It takes two parameters: the item to be added and the playlist to which it should be added. The method then returns the updated playlist. Note how the item needs to conform to the MusicPlaylistAddable protocol.

For a simple example, you can add a song to a playlist like:

let updatedPlaylist = try await MusicLibrary.shared.add(song, to: playlist)

Adding Songs to a Playlist

By default, the add method can only add one song at a time to a playlist. This means that if you want to add multiple songs to a playlist, you need to loop through the collection of songs and call the add method for each song:

import MusicKit

func addSongsToPlaylist(songs: MusicItemCollection<Song>, to playlist: Playlist) async {
  for song in songs {
    do {
      let _ = try await MusicLibrary.shared.add(song, to: playlist)
    } catch {
      print("Error adding song \(song.title) to the playlist \(playlist.name): \(error)")
    }
  }
}

In the above example, you iterate through each song and call the add method of the MusicLibrary class to add the song to the specified playlist. If the addition is successful, you can handle it accordingly. If an error occurs during the addition, handle or log the error.

Using MusadoraKit

If you are looking for a more straightforward way to add songs to a playlist in MusicKit, you can use my MusadoraKit. MusadoraKit is a library that simplifies the process of adding songs to a playlist by providing a convenient method called add(songs:to:).

Here is an example of how to use MusadoraKit to add an array of songs to a playlist:

let songs: MusicItemCollection<Song> = [...] // New songs to add
let playlist: Playlist = [...] // Obtain this from the music library

do {
    let success = try await MLibrary.add(songs: songs, to: playlist)

    if success {
        print("Songs successfully added to playlist.")
    } else {
        print("Failed to add songs to playlist.")
    }
} catch {
    print("Error adding songs to playlist: \(error)")
}

In the above example, you pass a the collection of songs and the playlist object to the add(songs:to:) method of MusadoraKit’s MLibrary. The method internally maps the song IDs and calls the add(songIDs:to:) method, which adds the songs to the playlist using the Apple Music API. The method returns a boolean value indicating whether the songs were successfully added to the playlist.

MusadoraKit simplifies the process of working with MusicKit, making it easier for you!

Conclusion

Adding songs to a playlist using MusicKit is a straightforward process. And MusadoraKit makes it much easier!

Happy coding, and keep the playlist playing!

Book

Exploring MusicKit and Apple Music API

Unlock the full power of MusicKit & Apple Music APIs in your apps with the best guide! Use code musickit-blog for a limited-time 35% discount!

Written by

Rudrank Riyam

Hi, my name is Rudrank. I create apps for Apple Platforms while listening to music all day and night. Author of "Exploring MusicKit". Apple WWDC 2019 scholarship winner.