MusicKit

RSS for tag

Let users play Apple Music and their local music library from your app using MusicKit.

Posts under MusicKit tag

137 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Editing a Library Playlist (MusicKit: iOS 16 beta)
I've just begun to dip my toes into the iOS16 waters. One of the first things that I've attempted is to edit a library playlist using: try await MusicLibrary.shared.edit(targetPlaylist, items: tracksToAdd) Where targetPlaylist is of type MusicItemCollection<MusicKit.Playlist>.Element and tracksToAdd is of type [Track] The targetPlaylist was created, using new iOS16 way, here: let newPlaylist = try await MusicLibrary.shared.createPlaylist(name: name, description: description) tracksToAdd is derived by performing a MusicLibraryRequest on a specific playlist ID, and then doing something like this: if let tracksToAdd = try await playlist.with(.tracks).tracks {    // add tracks to target playlist } My problem is that when I perform attempt the edit, I am faced with a rather sad looking crash. libdispatch.dylib`dispatch_group_leave.cold.1:     0x10b43d62c <+0>:  mov    x8, #0x0     0x10b43d630 <+4>:  stp    x20, x21, [sp, #-0x10]!     0x10b43d634 <+8>:  adrp   x20, 6     0x10b43d638 <+12>: add    x20, x20, #0xfbf          ; "BUG IN CLIENT OF LIBDISPATCH: Unbalanced call to dispatch_group_leave()"     0x10b43d63c <+16>: adrp   x21, 40     0x10b43d640 <+20>: add    x21, x21, #0x260          ; gCRAnnotations     0x10b43d644 <+24>: str    x20, [x21, #0x8]     0x10b43d648 <+28>: str    x8, [x21, #0x38]     0x10b43d64c <+32>: ldp    x20, x21, [sp], #0x10 ->  0x10b43d650 <+36>: brk    #0x1 I assume that I must be doing something wrong, but I frankly have no idea how to troubleshoot this. Any help would be most appreciated. Thanks. @david-apple?
10
0
2.6k
Sep ’23
Thoughts on MusicLibraryRequest as a replacement for MPMediaQuery
I'm very excited about the new MusicLibrary API, but after a couple of days of playing around with it, I have to say that I find the implementation of filtering MusicLibraryRequests a little confusing. MPMediaQuery has a fairly extensive list of predicates that can be applied, including string and persistentID comparisons for artist, album artist genre, and more. It also lets you filter on an item’s title. MusicLibraryRequests let you filter on the item’s ID, or on its MusicKit Artist and Genre relationships. To me, this seems like it adds an extra step.  With an MPMediaQuery, if I wanted to fetch every album by a given artist, I’d apply an MPMediaPropertyPredicate looking at MPMediaItemPropertyAlbumArtist and compare the string. It was also easy to change the MPMediaPredicateComparison to .contains to match more widely. If I wanted to surface albums by “Aesop Rock” or “Aesop Rock & Blockhead,” I could use that. In the MusicLibraryRequest implementation, it looks like I need to perform a MusicLibraryRequest<Artist> first in order to get the Artist objects. There’s no filter for the name property, so if I don’t have their IDs, I’ve got to use filter(text:). From there, I can take the results of that request and apply them to my MusicLibraryRequest<Album> using the filter(matching:memberOf) function.  I could use filter(text:) on the MusicLibraryRequest<Album>, but that filters across multiple properties (title and artistName?) and is less precise than defining the actual property I want to match against. I think my ideal version of the MusicLibraryRequest API would offer something like filter(matching:equalTo:) or filter(matching:contains:) that worked off of KeyPaths rather than relationships. That seems more intuitive to me. I’m not saying we need every property from every filterable MPMediaItemProperty key, but I’d love to be able to do it on title, artistName, and other common metadata. That might look something like: filter(matching: \.title, contains: “Abbey Road”) filter(matching: \.artistName, equalTo: “Between The Buried And Me”) I noticed that filter(text:) is case insensitive, which is awesome, and something I’ve wanted for a long time in MPMediaPropertyPredicate. As a bonus, it would be great if a KeyPath based filter API supported a case sensitivity flag. This is less of a problem when dealing with Apple Music catalog content, but users’ libraries are a harsh environment, and you might have an artist “Between The Buried And Me” and one called “Between the Buried and Me.” It would be great to get albums from both with something like: filter(matching: \.artistName, equalTo: “Between The Buried And Me”, caseSensitive: false)  I've submitted the above as FB10185685. I also submitted another feedback this morning regarding filter(text:) and repeating text as FB10184823. My last wishlist item for this API (for the time being!) is exposing the MPMediaItemPropertyAlbumPersistentID as an available filter attribute. I know, I know… hear me out. If you take a look at the other thread I made today, you’ll see that due to missing metadata in MusicKit, I still have some use cases where I need to be able to reference an MPMediaItem and might need to fetch its containing MPMediaItemCollection to get at other tracks on the album. It would be nice to seamlessly be able to fetch the MPMediaItemCollection or the library Album using a shared identifier, especially when it comes to being able to play the album in MusicKit’s player rather than Media Player’s.  I've submitted that list bit as FB10185789 Thanks for bearing with my walls of text today. Keep up the great work!
10
1
2.7k
3w
MusicKit Dev Token Refresh
I am trying to follow along with this in order to auto generate my dev token on requests to MusicKit, but I am getting an error about by identifier, which was configured Link: https://developer.apple.com/documentation/musickit/using-automatic-token-generation-for-apple-music-api Error: 2022-04-26 14:12:06.353589-0400 [6885:431407] [DataRequesting] Failed retrieving developer token: Error Domain=ICErrorDomain Code=-8200 "Media API Token Service responded with status code: Not Found (404). This suggests that "<set_bundle_ID>" was likely not registered as a valid client identifier." UserInfo={NSDebugDescription=Media API Token Service responded with status code: Not Found (404). This suggests that "<set_bundle_ID>" was likely not registered as a valid client identifier., NSUnderlyingError=0x2827669a0 {Error Domain=AMSErrorDomain Code=301 "Invalid Status Code" UserInfo={NSLocalizedDescription=Invalid Status Code, AMSURL=https://sf-api-token-service.itunes.apple.com/apiToken?REDACTED, AMSStatusCode=404, AMSServerPayload={     message = "Client not found";     status = 40402; }, NSLocalizedFailureReason=The response has an invalid status code}}}. Throwing .developerTokenRequestFailed. error getting token
4
0
1.7k
Oct ’23
How can I play Apple Music Live Radio Station?
Hello, I'm using systemMusicPlayer to play Apple Music Live Radio Station got from Apple Music API. But it doesn't work. How can I do that? Error: Test[46751:13235249] [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=6 "Failed to prepare to play" UserInfo={NSDebugDescription=Failed to prepare to play} My implementation:    let musicPlayerController = MPMusicPlayerController.systemMusicPlayer musicPlayerController.beginGeneratingPlaybackNotifications()      musicPlayerController.setQueue(with: "ra.978194965")     musicPlayerController.play() API response: { “id”: “ra.978194965”, “type”: “stations”, “href”: “/v1/catalog/us/stations/ra.978194965”, “attributes”: { “artwork”: { “width”: 4320, “url”: “https://is2-ssl.mzstatic.com/image/thumb/Features114/v4/e5/10/76/e5107683-9e51-ebc5-3901-d8fbd65f2c2a/source/{w}x{h}sr.jpeg”, “height”: 1080, “textColor3”: “332628”, “textColor2”: “120509”, “textColor4”: “33272a”, “textColor1”: “000000”, “bgColor”: “f4f4f4”, “hasP3”: false }, “url”: “https://music.apple.com/us/station/apple-music-1/ra.978194965”, “mediaKind”: “audio”, “supportedDrms”: [ “fairplay”, “playready”, “widevine” ], “requiresSubscription”: false, “name”: “Apple Music 1”, “kind”: “streaming”, “radioUrl”: “itsradio://music.apple.com/us/station/ra.978194965”, “playParams”: { “id”: “ra.978194965”, “kind”: “radioStation”, “format”: “stream”, “stationHash”: “CgkIBRoFlaS40gMQBA”, “mediaType”: 0 }, “editorialNotes”: { “name”: “Apple Music 1”, “short”: “The new music that matters.”, “tagline”: “The new music that matters.” }, “isLive”: true } },``` Thank you! Best regards, MichaelNg
2
0
1.9k
Aug ’23
MPMusicPlayerController queue information
Is there a way to get the current queue items from an MPMusicPlayerController? I need to know when the items I've set to the queue finish playing completely but cannot find any way to do this. I am not using MusicKit but setting the queue via play parameters. From what I can tell so far, after the queue finishes playing, it pauses and resets to the first item in the queue. So even after playback is done, there is no way to know that it finished on its own.
2
0
912
May ’24
How to detect a song end?
I'm playing library items (MPMediaItem) and apple music tracks (Track) in MPMusicPlayerApplicationController.applicationQueuePlayer, but I can't use the actual Queue functionality because I can't figure out how to get both media types into the same queue. If there's a way to get both types in a single queue, that would solve my problem, but I've given up on that one. Because I can't use a queue, I have to be able to detect when a song ends so that I can put the next song in the queue and play it. The only way I can figure out to detect when a song ends is by watching the playBackState, and I've actually got that pretty much working, but it's really ugly, because you get playBackState of paused when a song ends, and when a bluetooth speaker disconnects, etc. The only answer I've been able to find on the internet is to watch the MPMusicPlayerControllerNowPlayingItemDidChange, and when that fires, and the nowPlayingItem is NIL, a song ends.. but that's not the case. When a song ends, the nowPlayingItem remains the same. There's got to be an answer to this problem, right?
12
3
3.9k
Sep ’23
How to get the album info for a song fetched by MusicDataRequest?
I'm slowly learning the new MusicKit beta for swift. I've learned to successfully retrieve tracks of type Song using MusicDataRequest, using the following: ... let countryCode = try await MusicDataRequest.currentCountryCode if let url = URL(string: "https://api.music.apple.com/v1/catalog/\(countryCode)/songs?filter[isrc]=\(isrc)") {   let dataRequest = MusicDataRequest(urlRequest: URLRequest(url: url))   let dataResponse = try await dataRequest.response() ... However, when I decode the data, there does not seem to be any album information that I can see. I've tried adding includes=albums to the URL, but I don't think that's the right approach, because when I veiw the Song struct in MusicKit, I don't see a reference to an Album type anywhere. Any advice on how to retrieve the album information would be most appreciated. Thanks.
7
0
2.8k
Apr ’24
Upstream Service Error when using MusicDataRequest
Hey there! I'm trying to use MusicDataRequest to fetch the contents of a user's library. Most of the documented endpoints I've tried seem to be working as expected, but the /me/library/artists and /me/library/albums endpoints are consistenty giving me a 500 Upstream Service Error. Here's an example of my code, and the resulting error: let url = URL(string: "https://api.music.apple.com/v1/me/library/albums")! let request = MusicDataRequest(urlRequest: URLRequest(url: url)) do { let response = try await request.response()     let string = String(data: response.data, encoding: .utf8)!     print("success: \(string)") } catch {     print("error: \(error)") } MusicDataRequest.Error(   status: 500,   code: 50001,   title: "Upstream Service Error",   detailText: "Error fetching library content",   id: "5OFXMJAGNU2WCTDKNAYYP4BJXI",   originalResponse: MusicDataResponse(    data: 153 bytes,    urlResponse: <NSHTTPURLResponse: 0x0000000280f04dc0>   ) ) If I replace /albums with /songs or /playlists in the above code everything works as expected. Is there something I'm missing from the albums and artists requests? Or is this a bug with the API?
12
0
2.8k
Feb ’24
MusicKit: developer token request failed
The MusicKit video states that you just enable "MusicKit" in your application identifier and "you're done!" Ok, so I did that, and I'm seeing the following error when trying to run a song query: [DataRequesting] Failed retrieving MusicKit tokens: Error Domain=ICErrorDomain Code=-8200 "Media API Token Service's response was invalid (status code: Unauthorized (401))." UserInfo={NSDebugDescription=Media API Token Service's response was invalid (status code: Unauthorized (401))., NSUnderlyingError=0x6000023a0c60 {Error Domain=AMSErrorDomain Code=301 "Invalid Status Code" UserInfo={NSLocalizedDescription=Invalid Status Code, AMSURL=https://sf-api-token-service.itunes.apple.com/apiToken?REDACTED, AMSStatusCode=401, AMSServerPayload={ status = verificationFailure; }, NSLocalizedFailureReason=The response has an invalid status code}}}. Throwing .developerTokenRequestFailed. Is this just broken on Apple's side? Is there some other magic string that needs to be added to the plist other than NSAppleMusicUsageDescription?
7
0
3.2k
Mar ’24
ERROR_FAILED_TO_VERIFY_JWT error when trying to link with Apple Music
I want to use Apple Music using MusicKit. I've created MusicKit identifier and private key by following all the steps mentioned here: https://help.apple.com/developer-account/#/devce5522674 I have my Team ID, the Music key ID and the private key (.p8 file) with me. I tried to generate the required JWT token by using many scripts that were mentioned in similar questions asked here, but none of them have worked so far. When I try to authenticate, I'm getting an error ERROR_FAILED_TO_VERIFY_JWT. Ref: Codes I've tried to generate the JWT token from: Thread 130168 - https://developer.apple.com/forums/thread/130168 A nice and simple blog by Lee Martin [Blog - Creating an Apple Music API Token] Thread 79074 - https://developer.apple.com/forums/thread/79074 Many other links But sadly, none of them worked and I had to post this question. I have tried the sample Android app: https://developer.apple.com/download/more/?=Android%20MusicKit After authentication, the page goes on with an infinite loader, which I believe must be because of the same error ERROR_FAILED_TO_VERIFY_JWT Also tried with this HTML page: <html> <head> <meta name="apple-music-developer-token" content="the-JWT-token-generated-using-the-reference-links"> <meta name="apple-music-app-name" content="My App Name"> <meta name="apple-music-app-build" content="1978.4.1"> </head> <body> <button id="apple-music-authorize"></button> <button id="apple-music-unauthorize"></button> </body> <script src="link-to-musickit.js"></script> <script> let music = MusicKit.getInstance(); &#9;&#9;music.player.play(); &#9;&#9;music.authorize().then(function() { &#9;&#9;&#9;&#9;music.player.play(); &#9;&#9;}); &#9;&#9;music.authorize().then(function() { &#9;&#9;&#9;&#9; music.api.library.albums.then(function(cloudAlbums) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;// user's cloudAlbums &#9;&#9;&#9;&#9;}); &#9;&#9;}); </script> </html>
4
0
2.6k
Sep ’23
MPMusicPlayerController prepareToPlay errors
I'm getting a variety of errors when I call prepareToPlay on the MPMusicPlayerController. Sometimes they happen, sometimes they don't. I'm trying to play songs from the Apple Music service. When I don't get the errors, it plays just fine. I have iOS v13.5.1 on my iPhone Xs and I'm using Xcode 11.5. This is my code: let applicationMusicPlayer = MPMusicPlayerController.applicationMusicPlayer applicationMusicPlayer.setQueue(with: [trackID]) applicationMusicPlayer.prepareToPlay(completionHandler:{ error in if let error = error { print(error.localizedDescription) return } DispatchQueue.main.async{ applicationMusicPlayer.play() } } These are the various errors I'm getting: [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=2 "Queue was interrupted by another queue" UserInfo={NSDebugDescription=Queue was interrupted by another queue} [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=9 "Preparing queue timed out" UserInfo={NSDebugDescription=Preparing queue timed out} [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=6 "Failed to prepare to play" UserInfo={NSDebugDescription=Failed to prepare to play} [SDKPlayback] applicationQueuePlayer _establishConnectionIfNeeded timeout [ping did not pong]
7
0
4.3k
Mar ’24
Delay When Playing or Skipping Songs
I get a few seconds delay intermittently when playing or skipping a song (even ones downloaded). This functionality works perfectly in the native music app or the control centre widget. Even the "Adding Content To Apple Music" sample code app is very laggy. This bug needs to fixed because it makes users think the app is frozen, thus ruining the app user experience.Please submit your own bug reports to apple if you are having this problem so we can get this issue resolved faster!
17
0
16k
Sep ’23
Getting audio from MPMusicPlayerController for visualization?
Howdy,I'm hoping to start a conversation about getting access to live audio data for items playing from Apple Music.As background, we've been authoring and selling music visuals on OS X and other platforms for over 13 years. We are behind some of the visualizers that reside in iTunes to this day. Our latest product is an iOS app called Tunr, and it features a unique UI for audio/streaming services and protocols, unifying the user music experience in the way iTunes 1.0 set out to do -- most importantly, we seek to pull multiple music sources under a single roof and do it in the context of mobile and streaming. For easier reference, grab Tunr from the app store and play with it.As we rollout Tunr, we're getting requests to add support for Apple Music. MusicKit, like other ReST interfaces that we support (SoundCloud, Spotify, iHeartRadio, etc), fits into our model by design. However, because MusicKit requires playback through MPMusicPlayerController, there isn't a way to tap into the live audio/PCM samples (so that the user sees Tunr's realtime visuals react to the currently playing audio). In contrast, for example, the Spotify SDK has its own player API but exposes an AUGraph, allowing Tunr to call AudioUnitAddRenderNotify() where we can read the PCM data for visualization.In general, not offering access to raw PCM data traces back to DRM policies originating in the 2000s. I also submit that the way apps like Tunr use live audio data is disjoint from the DRM politics and debate. However, in practice, we all know it's hard to disentangle the two, and that’s likely why AVPlayer also never had a live audio tap. For this reason, we had to develop our own player for Tunr.As a proposed solution, I’d like to suggest that MPMediaPlayback be extended such that a callback gets downsampled audio PCM data to, say, 5k-11k samples/sec. This sample rate is too low for it to be "ripped" but would be sufficient for rendering visualizations.In any case, I at least wanted to stimulate conversation on this topic. Alternatively, it would be to get access to the audio stream to decode and play for a given Apple music item, but I'm pretty sure that's a non-starter.Suggestions? Thoughts? Other ideas?Andy O'MearaSoundSpectrum CTO
4
0
11k
Oct ’23