Meet MusicKit for Swift

RSS for tag

Discuss the WWDC21 session Meet MusicKit for Swift.

View Session

Posts under wwdc21-10294 tag

37 results found
Sort by:
Post not yet marked as solved
32 Views

Getting the album title from the queue's current entry item

I'm trying to get the album title from the current entry in the Queue of ApplicationMusicPlayer. I'm using the following code for this purpose - let queue = ApplicationMusicPlayer.shared.queue let item = queue.currentEntry?.item if case let .song(song) = item { print(song.albumTitle) } But it is returning a nil value. If I print the debug description of the song, I get the other details. Song(   id: "1524813873",   title: "'Til We Die",   artistName: "Slipknot",   discNumber: 1,   hasLyrics: "false",   releaseDate: "2008-08-20",   trackNumber: 15 ) If I do a request to MusicCatalogResourceRequest<Song>, and print the debug description, I get the album title as well. let queue = ApplicationMusicPlayer.shared.queue let item = queue.currentEntry?.item if case let .song(song) = item { do { let musicRequest = MusicCatalogResourceRequest<Song>(matching: \.id, equalTo: song.id) let response = try await musicRequest.response() print(response.items.first.debugDescription) } catch { print(error) } } Song(   id: "1524813873",   title: "'Til We Die",   albumTitle: "All Hope Is Gone (Deluxe Edition)",   artistName: "Slipknot",   composerName: Chris Fehn, Corey Taylor, Craig Jones, Jim Root, Joey Jordison, Mick Thomson, Paul Gray, Shawn "Clown" Crahan & Sid Wilson,   discNumber: 1,   duration: 345.693,   genreNames: [     "Metal",     "Music",     "Rock"   ],   hasLyrics: "true",   isrc: "NLA320887352",   releaseDate: "2008-08-20",   trackNumber: 15 ) Is this a bug or intentional? Thanks!
Asked
by snuff4.
Last updated
.
Post marked as solved
118 Views

How to fetch content like the Browse tab in Apple Music

Hello, Is there any way to get content like what is displayed in the Browse tab of Apple Music using MusicKit or Apple Music API? I checked the contents of the default recommendations in the Apple Music API, and these were my personal recommendations. Is it possible to get common recommendations?
Asked
by birnimal.
Last updated
.
Post marked as solved
246 Views

Setting playbackRate in MusicKit for Swift (beta)

Hi! I'm trying out the new MusicKit for Swift (iOS 15 beta). Really liking it! But I'm seeing a weird issue with setting state.playbackRate to anything other than 1.0 when playing. The issue appears to be that the player keeps trying to reset itself to a playbackRate of 1.0. If I set it to 0.5 or 2.0 it still plays the track back at a playbackRate of 1.0. Strangely, about 5% of attempts to change it are actually successful on the ApplicationMusicPlayer. SystemMusicPlayer changes more reliably at maybe a 20% success rate, in my testing. It seems to be happening during/after preparing the track. If I swap out the player's queue while it's preparing to play, I can get it to reliably throw a prepareToPlay error and, upon doing so, it then accepts the playbackRate change to a non-1.0 value. I've tried setting the playbackRate before playing, after playing, and even both! Through observing the playbackRate property I can see that my alterations seem to stick for maybe 0.5 sec as the track loads, then the rate changes back to 1.0 as the song begins to play. I understand it's still in beta so if the answer is simply "wait for release" then that's fine! But I'd like to know if anyone has found a way to reliably alter the playbackRate, as I'm in the middle of scouting a new project that will depend on it. Some detail into my setup: I'm doing this in the WWDC21 project UsingMusicKitToIntegrateWithAppleMusic (which didn't compile out of the box for me until I reworked some of it). My setup is: iPadOS 15 beta 5 (19a5318f) on an iPad Air 2. Xcode v13.0 beta 5 (13A5212g). MacOS Big Sur 11.4. Thanks!
Asked Last updated
.
Post not yet marked as solved
221 Views

Retrieving a list of tracks from a library playlist

I'm trying to do something that I though would be simple; however, I'm tripping up on something... In brief, I want to get all tracks from a playlist in an AppleMusic authorized user's playlist with the following function:     func getTracksFromAppleMusicPlaylist(playlistId: MusicItemID) async throws -> [Track]? {         print("Fetching AppleMusic Playlists...")         print("Playlist ID: \(playlistId)")         var playlistTracks: [Track]? = []         do {             var playlistRequest = MusicCatalogResourceRequest<Playlist>(matching: \.id, equalTo: playlistId )             playlistRequest.properties = [.tracks]             let playlistResponse = try await playlistRequest.response()             print("Playlist Response: \(playlistResponse)")             let playlistWithTracks = playlistResponse.items             let tracks = playlistWithTracks.flatMap { playlist -> MusicItemCollection<Track> in                 playlist.tracks ?? []             }             playlistTracks = tracks.count > 1 ? tracks : nil         } catch {             print("Error", error)             // handle error         }         return playlistTracks     } This function results in the following error: 2021-08-28 04:25:14.335455+0700 App[90763:6707890] [DataRequesting] Failed to perform MusicDataRequest.Context(   url: https://api.music.apple.com/v1/catalog/us/playlists/p.7XxxsXxXXxX?include=tracks&omit%5Bresource%5D=autos,   currentRetryCounts: [.other: 1] ) with MusicDataRequest.Error(   status: 404,   code: 40400,   title: "Resource Not Found",   detailText: "Resource with requested id was not found",   id: "QMK7GH4U7ITPMUTTBKIOMXXXX",   originalResponse: MusicDataResponse(     data: 159 bytes,     urlResponse: <NSHTTPURLResponse: 0x00000002820c0b60>   ) ). The playlistID being used is a value that has been picked from an existing playlist in the user's library, via a function that uses this code snippet: if let url = URL(string: "https://api.music.apple.com/v1/me/library/playlists?limit=100") {                let dataRequest = MusicDataRequest(urlRequest: URLRequest(url: url)) ... The only thing I can think of is that the playlistId from the above snippet is converted to a string when decoding into a struct, after which it is changed back to a MusicItemID with an init, like MusicItemID(playlistId). Any thoughts? Because I'm at a loss...
Asked Last updated
.
Post marked as solved
348 Views

Play songs from library

Hello, I was trying to use the new ApplicationMusicPlayerController with an album from the music library. In my test code I am searching for the artist "LUWTEN" in my personal library. In my personal library there are two albums that will be found. When I try to play the first album I will get the error MSVEntitlementUtilities - Process .. PID[648] - Group: com.apple.private.tcc.allow - Entitlement: kTCCServiceMediaLibrary - Entitled: NO - Error: (null). Is there a way to play library music with the new ApplicationMusicPlayerController?     func searchLuwten () {         struct MyAlbums : Codable {             let results : Result         }                  struct Result : Codable {             let libraryAlbums : Albums             enum CodingKeys: String, CodingKey {                 case libraryAlbums = "library-albums"             }         }         struct Albums : Codable {             let href : String             let data : [LibraryAlbum]         }                  struct LibraryAlbum : Codable, PlayableMusicItem {             let id : MusicItemID             let attributes : Attributes                          var playParameters: PlayParameters? {                 attributes.playParams             }         }                  struct Attributes : Codable {             let name : String             let playParams : PlayParameters         }                  detach {             let term = "LUWTEN"             var components = URLComponents()             components.scheme = "https"             components.host   = "api.music.apple.com"             components.path   = "/v1/me/library/search"             components.queryItems =  [                 URLQueryItem (name: "term", value: term),                 URLQueryItem (name: "types", value: "library-albums")             ]                          guard let url = components.url else {                 return             }                          let dataRequest = MusicDataRequest(urlRequest: URLRequest(url: url))             let dataResponse = try await dataRequest.response()                          let decoder = JSONDecoder()             let albumResponse = try decoder.decode (MyAlbums.self, from: dataResponse.data)             let player = ApplicationMusicPlayer.shared             player.setQueue (with: albumResponse.results.libraryAlbums.data[0])             player.play()                      }     }
Asked
by dongelen.
Last updated
.
Post marked as solved
264 Views

Searching for a track with MusicKit Swift Beta

I'm trying to perform a search for a song by album, artist, & title in the cases when I don't know the song's id (or if there is no isrc match) Reading the docs, it seems that I can only search for one term at a time, but against a list of MusicCatalogSearchable Types So my strategy would be to search for albums by name, then filter the results by artist and title. Two questions here, really: Is the above a good strategy, or is there a better way to do this? For the life of my I cannot figure out from the docs, what to put in place of [MusicCatalogSearchable.Album] in the below. var albumRequest = MusicCatalogSearchRequest(term: album.name, types: [MusicCatalogSearchable.Album]) Xcode doesn't like the above and gives the following error: Type 'MusicCatalogSearchable' has no member 'Album' Sadly, everything I've tried, results in an error. When I look in MusicKit, I see the below, which seems empty to me: @available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) public protocol MusicCatalogSearchable : MusicItem { } What am I missing?
Asked Last updated
.
Post marked as solved
169 Views

How to make a playlist public/create a public playlist?

Hey everyone, I am creating playlist via the MusicKit API and by default it creates the playlist in the users library and the isPublic attribute is set to false. Is there a way to make the playlist public at the time of creation? (Only way to change isPublic = true at this time seems to be through the Music app right now)
Asked Last updated
.
Post marked as solved
474 Views

How can add songs to a playlist or create a new playlist from my APP?

Hi, I would like to be able to create a playlist from my app or add songs to an existing selected playlist in the user music library, How can I do that ? Is there an API in MusicKit to do that? The Shazam app is doing something similar with the My Shazam Songs playlist... Thanks
Asked
by aleroot.
Last updated
.
Post not yet marked as solved
111 Views

So can we develop a music app and release it?

We are afraid that apple will reject the app for sharing the similar functionality with the Apple Music app.
Asked Last updated
.
Post not yet marked as solved
122 Views

Cache SwiftUI ArtworkImage

Hi, is there a way to cache the data from the SwiftUI ArtworkImage across App starts and maybe even for offline use? Best regards Julian
Asked
by juka1205.
Last updated
.
Post marked as solved
162 Views

How to fetch next batch of albums for an Artist?

Hello, I am fetching and displaying the .fullalbums for an Artist through the MusicKit api. The JSON response returned has a hasNextBatch: true value, but I am unsure how to fetch and display the next batch. Is this something that can be intelligently retrieved though some MusicKit functionality or does one have to perform another data request to fetch the next batch?
Asked Last updated
.
Post not yet marked as solved
242 Views

Cannot decode library songs response for a non-Apple Music item

Hi there! I am fetching library songs using the endpoint: https://api.music.apple.com/v1/me/library/songs Here's the code snippet - struct Songs: Decodable { let data: [Song] } public func librarySongs() async throws { let url = URL(string: "https://api.music.apple.com/v1/me/library/songs")   guard let url = url else { return }   let dataRequest = MusicDataRequest(urlRequest: URLRequest(url: url)) do { let dataResponse = try await dataRequest.response() print(dataResponse.debugDescription) let response = try JSONDecoder().decode(Songs.self, from: dataResponse.data) } catch { print("**ERROR**") print(error) print(error.localizedDescription)     } } Trying to decode it using a custom struct gives me the following error. - **ERROR** keyNotFound(CodingKeys(stringValue: "artistName", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 20", intValue: 20), CodingKeys(stringValue: "attributes", intValue: nil)], debugDescription: "No value associated with key CodingKeys(stringValue: \"artistName\", intValue: nil) (\"artistName\").", underlyingError: nil)) The data couldn’t be read because it is missing. On digging through the response, I found that one of the songs doesn't have an artist name because it is just a recording of my song I added to the library through GarageBand. In this case, what should be the approach?
Asked
by snuff4.
Last updated
.
Post not yet marked as solved
135 Views

MusicKit: Artist artwork?

I was listing the library artists and couldn't figure out a way to show the artist artwork. Is there a way to fetch it? Under Artist music item, I couldn't find an artwork instance property. Is it due to copyright/legal issues?
Asked
by snuff4.
Last updated
.
Post not yet marked as solved
282 Views

MusicKit Sample Code errors

In Xcode 13 beta 4, the Sample Code Using MusicKit to Integrate with Apple Music has compiler errors around the player.play() calls in handleTrackSelected and handlePlayButtonSelected. The error is "async call in a function that does not support concurrency / call can throw, but is not marked with try and the error is not handled" Would it be possible to include a fix for this error in the sample code - or could somebody share a fix here in the forums? Thanks so much!
Asked
by RanLearns.
Last updated
.