MusicKit

RSS for tag

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

MusicKit Documentation

Posts under MusicKit tag

142 Posts
Sort by:
Post not yet marked as solved
4 Replies
1.2k Views
Hello! I am having trouble setting start times for songs when using the ApplicationMusicPlayer. When I initialize a new MusicPlayer.Queue.Entry using the following constructor, I am seeing strange results: init( _ playableMusicItem: PlayableMusicItem, startTime: TimeInterval? = nil, endTime: TimeInterval? = nil ) It appears that any value I provide for startTime is also applied to the endTime. For example: MusicPlayer.Queue.Entry(playable, startTime: TimeInterval(30), endTime: TimeInterval(183)) provides the following console output: MusicPlayer.Queue.Entry(id: "3D6A3DA3-595E-4657-8DBA-DDD245BBB7EF", transientItem: PlayableMusicItem, startTime: 30.0, endTime: 30.0) I have also tried setting the endTime to nil with the same result. Does anyone have any experience setting start times for songs using the MusicKit ApplicationMusicPlayer? Any feedback is greatly appreciated!
Posted
by
Post not yet marked as solved
2 Replies
878 Views
I am trying to offer my users a wide variety of playlists, like Apple Music does in the "explore" section. I fetched the charting playlists for the current storefront, but that's as far as I get. For example, I fetch the top charts genres first. If a user selects a genre I want to display the playlists for this genre, so I call the charts endpoint with the genre as the id but I can't get a response. path = "/v1/catalog/\(storefrontID)/charts" components.queryItems = [ URLQueryItem(name: "types", value: "playlists"), URLQueryItem(name: "chart", value: "most-played") ] if let id = id { let genreQuery = URLQueryItem(name: "genre", value: id) components.queryItems?.append(genreQuery) } Even weirder, I get exactly one genre "Musik" (which isn't a genre) with identifier "34" and storefrontId "de" where it works and I get my playlists. All other genre return empty responses. I try to use AppleMusic API with MusicKit as an addition, but there doesn't seem to be a solution for this problem either.
Posted
by
Post not yet marked as solved
6 Replies
3.4k Views
Hi there, I have a related forum thread here and a Feedback Assistant ticket open, but this issue seems different. Sometime within the last 2-3 weeks, code related to MusicLibrary has stopped working. None of my code has changed. For example, the below two snippets used to work fine:  for track in newTracks {    try await MusicLibrary.shared.add(track, to: targetPlaylist)  } try await MusicLibrary.shared.edit(targetPlaylist, items: items) newTracks and items are both fetched using: try await targetPlaylist.with(.tracks, preferredSource: .catalog).tracks Using preferredSource: .catalog was a workaround used to address the issue in the aforementioned post above. All iOS 16 capable functions are decorated with: @available(iOS 16, *) or in an if block: if #available(iOS 16, *) {... What's happening is that the following is showing up in the console: 2022-11-28 23:31:11.279648+0700 MyApp[38653:6736450] [core] Attempted to register account monitor for types client is not authorized to access: {(     "com.apple.account.iTunesStore" )} 2022-11-28 23:31:11.279718+0700 MyApp[38653:6736450] [Default] <ICUserIdentityStoreACAccountBackend: 0x282adb520> Failed to register for account monitoring. err=Error Domain=com.apple.accounts Code=7 "(null)" 2022-11-28 23:31:11.279758+0700 MyApp[38653:6736450] [Default] ICUserIdentity - Unable to retrieve DSID for userIdentity=<ICUserIdentity 0x2806eb120: [Active Account: <unresolved>]> - error=Error Domain=com.apple.accounts Code=7 "(null)" These errors are not caught by a do/catch block, but I assume they are related to the issue, and I believe they have to do with MyApp trying to access things that Music Kit thinks it's not supposed to. For example, if MyApp attempts to work with a playlist that it did not create, errors would be expected, thrown errors. The thing is that I know I'm working with resources that are created by MyApp. In fact, in trying to test this, I just tried to create a playlist with the below, and the same behavior is occurring: @available(iOS 16, *) func createPlaylist2(name: String, description: String) async -> MusicKit.Playlist? {     do {         Logger.log(.info, "Creating Playlist: \(name)")         Logger.log(.shrug, "Does this work?")         let newPlaylist = try await MusicLibrary.shared.createPlaylist(name: name, description: description) // <= Things stop here!         Logger.log(.success, "New playlist created: \(newPlaylist)") // <= this isn't logged.         return newPlaylist // <= nothing is returned     } catch {         Logger.log(.error, "Could not create new playlist: \(error)") // <= no error logged.     }     return nil } The result is: 2022-11-29 00:15:01.875064+0700 MyApp[38794:6760471] [core] Attempted to register account monitor for types client is not authorized to access: {(     "com.apple.account.iTunesStore" )} 2022-11-29 00:15:01.875372+0700 MyApp[38794:6760471] [Default] <ICUserIdentityStoreACAccountBackend: 0x283005720> Failed to register for account monitoring. err=Error Domain=com.apple.accounts Code=7 "(null)" 2022-11-29 00:15:01.876677+0700 MyApp[38794:6760323] [EntityQuery] Finished executing query in 0.000999928s 2022-11-29 00:15:01.889055+0700 MyApp[38794:6760323] [EntityQuery] Finished fetching results in 0.0120001s 2022-11-29 00:15:01.891235+0700 MyApp[38794:6760329] [core] Attempted to register account monitor for types client is not authorized to access: {(     "com.apple.account.iTunesStore" )} 2022-11-29 00:15:01.891684+0700 MyApp[38794:6760329] [Default] <ICUserIdentityStoreACAccountBackend: 0x283005720> Failed to register for account monitoring. err=Error Domain=com.apple.accounts Code=7 "(null)" 📘 Creating Playlist: TEST PLAYLIST 🤷🏻‍♀️ Does this work? 2022-11-29 00:15:06.697374+0700 MyApp[38794:6760329] [] nw_path_necp_check_for_updates Failed to copy updated result (22) What's really nasty is that errors are not thrown, so they can't be caught and handled in a catch block. I know that iOS 16.1 got released around the end of October, but I really don't know what's going on here. The behavior is showing up in both prod and when testing locally. Any help would be most appreciated. @JoeKhun: Did I miss the memo?
Posted
by
Post not yet marked as solved
4 Replies
1.8k Views
Hey All I've been looking at adding a visual representation of the song's first genre in my app and therefor was wondering if there's a list available somewhere of all the Genre's available in MusicKit and their IDs e.g. Genre(id: "21", name: "Rock", parent: Genre(id: "34", name: "Music")) So my questions: Is there a list of all IDs? Are these IDs the same in every country? The reason why I would want this is to have my visuals be safe for localization. For example: If I'd call my asset icon-electronic and then localize my app in dutch it would ask for icon-electronisch. I hope this makes sense and I hope I don't have to browse and save a list of all Genre's by hand haha
Posted
by
Post not yet marked as solved
1 Replies
859 Views
In my Developer account under Certificates, Identifiers &amp; Profiles --&gt; Keys, I cannot add the "Media Services (MusicKit, ShazamKit) key. I have an app identifier where the "MusicKit" App Service is selected. How can I get the key to be available for this app?
Posted
by
Post not yet marked as solved
1 Replies
1.6k Views
Hello everyone! I am using the web version of the Apple Music Kit API, and similar to how Apple is able to produce a user's year in rewind playlist showing the most played artists/songs from a year, I am trying to replicate it for either a year or all time. I have been searching the internet for days trying to figure it out, but I've been completely stuck. I am able to make the following HTTP request successfully. GET https://api.music.apple.com/v1/me/library/songs/ which returns back the user's library of songs, but I haven't figured out how to get the play count. I have tried adding a query like such ?extend=playCount, but that doesn't work. I can see here that the Swift Music Kit API is able to extend a play count property, but I haven't been able to figure it out for Web. Ideally, I am looking for an endpoint that just shows a user's top artist/tracks similar to Spotify, however, whenever I try to use the heavy in rotation endpoint here, it always returns an empty array. The way that I have described is the long-roundabout way where I'll have to fetch each individual song and sort by playCount. But if anyone happens to know how I can do either of the options I've described, it will be truly appreciated ! I've seen other forums posts from years ago, but hopefully there's been a discovered way. Thank you!
Posted
by
Post not yet marked as solved
3 Replies
1.9k Views
I'm making a request to get 10 artists with their top songs at once, but for some artists it will always fail with a 504. The response is also in HTML which leads to a decoding error. This is my code var request = MusicCatalogResourceRequest<Artist>(matching: \.id, memberOf: ids) request.properties = properties let response = try await request.response() where ids is MusicItemId. Below I have an input which will always fail 100% of the time, even when retried. 10 elements  - 0 : "51639"  - 1 : "331584"  - 2 : "120199"  - 3 : "45058"  - 4 : "284786497"  - 5 : "44984"  - 6 : "37299"  - 7 : "518462"  - 8 : "39525"  - 9 : "73568" Example response: [DataRequesting] Failed to parse body of response with status code Unknown (504):  <!DOCTYPE html> <html lang="en"> <head>   <style>     body {       font-family: "Helvetica Neue", "HelveticaNeue", Helvetica, Arial, sans-serif;       font-size: 15px;       font-weight: 200;       line-height: 20px;       color: #4c4c4c;       text-align: center;     }     .section {       margin-top: 50px;     }   </style> </head> <body> <div class="section">   <h1>&#63743;</h1>   <h3>Gateway Timeout</h3>   <p>Correlation Key: WFRI6Q5HXAUJYXGNRKQ6YTBYIM</p> </div> </body> </html> I have also tried batching these into 2 requests of 5 artists instead of 1 request of 10 artists which still fails. However, I do have sets of 10 artists that work fine. Anyone know why?
Posted
by
Post not yet marked as solved
4 Replies
1.2k Views
Hello there! I have a problem: when i create Music User Token via AppleMusicKit, it returns me token that expires after one or two days. But regarding to this threads - https://developer.apple.com/forums/thread/654814 https://developer.apple.com/forums/thread/685343 it should expire in 6 months! Do I need to consider something when creating a token so that its lifetime will be 6 months and not 2 days? Maybe something with developer token or with MusicKit? Maybe something in apple account? p.s. i tried to find solution of this problem in internet and noticed that many other people have such problem too. And no one got any answers expect that token should live 6 months.
Posted
by
Post not yet marked as solved
1 Replies
699 Views
Hi, I’m looking at using MusicKit in my watchOS app however I don’t seem to have any method of being able to play the audio though the recommended use of MPMusicPlayerController since it isn’t available on watchOS. This method works fine for iOS and iPadOS but not watchOS which seems bizarre considering we have full access to MusicKit but no way to actually play any audio. I’m trying to build an app that includes Apple Music through MusicKit but don’t have any way to actually play the audio. Is there a technical reason for this and if so is there any other way to play audio from MusicKit on watchOS. The docs for MPMusicPlayerController can be found here: https://developer.apple.com/documentation/mediaplayer/mpmusicplayercontroller
Posted
by
Post not yet marked as solved
2 Replies
470 Views
Hi, . As my understading, I know that id: MusicItemID The unique identifier for the song. Threfore, I want to try to retreive the specific song I want by using MusicItemID : let request = MusicCatalogResourceRequest<Song>(matching: \.id, equalTo: //MusicItemID) let response = try await request.response() guard let song = response.items.first else { return } However, where can I find the MusicItemID for the song I want ? Thank you so much
Posted
by
Post not yet marked as solved
4 Replies
1.5k Views
I'm using applicationQueuePlayer in my application. I set Queue for it and it plays music. It was working fine in the app installed on my phone, but after phone was updated to iOS 16.4 it stopped working (see errors below). When I remove app from phone and recompiled and re-installed it to that phone, player started working normally. But when I replaced container via Xcodes Device and Simulators to previously saved - it stopped working again. Re-installing it on top of existing didn't fix it. It was only working if removed from phone completely and then installed from Xcode "from scratched". This started happening after phone update to 16.4. When I installed app "from scratch" - it was working fine, but when 16.4.1 was release couple of days ago and I installed it on a phone, it again broke the applicationQueuePlayer in my app. Same thing - removing app from phone and installing from scratch from Xcode makes it work, but restoring old container via Devices and Simulators breaks it again. I presume it has something to do with entitlements, but can't find any notes or info. Please help! Errors in log after attempting to start playing a title: 2023-04-12 14:56:19.400111-0400 MicyclePro[26736:2608042] [core] Attempted to register account monitor for types client is not authorized to access: {( "com.apple.account.iTunesStore" )} 2023-04-12 14:56:19.400284-0400 MicyclePro[26736:2608042] [Default] <ICMonitoredAccountStore: 0x2834ef390> Failed to register for account monitoring. err=Error Domain=com.apple.accounts Code=7 "(null)" 2023-04-12 14:56:20.407123-0400 MicyclePro[26736:2608714] [SDKPlayback] SYNC-WATCHDOG-1: Attempting to wake up the remote process 2023-04-12 14:56:20.619230-0400 MicyclePro[26736:2608439] [SDKPlayback] applicationController: xpc service connection interrupted 2023-04-12 14:56:20.619376-0400 MicyclePro[26736:2608042] [SDKPlayback] Failed to obtain synchronousRemoteObject: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service with pid 26768 created from an endpoint" UserInfo={NSDebugDescription=connection to service with pid 26768 created from an endpoint} 2023-04-12 14:56:20.619816-0400 MicyclePro[26736:2608512] [SDKPlayback] applicationMusicPlayer: connection invalidated 2023-04-12 14:56:20.620993-0400 MicyclePro[26736:2608042] [SDKPlayback] applicationQueuePlayer _establishConnectionIfNeeded timeout [ping did not pong] 2023-04-12 14:56:20.621094-0400 MicyclePro[26736:2608042] [SDKPlayback] Failed to obtain synchronousRemoteObject: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service created from an endpoint was invalidated: failed to check-in, peer may have been unloaded: mach_error=10000003." UserInfo={NSDebugDescription=The connection to service created from an endpoint was invalidated: failed to check-in, peer may have been unloaded: mach_error=10000003.} 2023-04-12 14:56:20.621376-0400 MicyclePro[26736:2608042] [SDKPlayback] applicationQueuePlayer _establishConnectionIfNeeded timeout [ping did not pong] 2023-04-12 14:56:20.621411-0400 MicyclePro[26736:2608042] [SDKPlayback] Failed to obtain synchronousRemoteObject: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service created from an endpoint was invalidated: failed to check-in, peer may have been unloaded: mach_error=10000003." UserInfo={NSDebugDescription=The connection to service created from an endpoint was invalidated: failed to check-in, peer may have been unloaded: mach_error=10000003.} 2023-04-12 14:56:20.628535-0400 MicyclePro[26736:2608042] [SystemGestureGate] <0x10761aa20> Gesture: System gesture gate timed out.
Posted
by
Post not yet marked as solved
0 Replies
474 Views
I'm developing a flutter app and using https://pub.dev/packages/music_kit to leverage MusicKit to handle the initial user permission request and generating the userToken. I then need to make requests to the Apple Music API from my server through a background task to retrieve the user's heavy rotation information which is used to recommend events. The initial authorization works as expected and generates a developer token and user token, but when I use the developer token and user token in a get request to https://api.music.apple.com/v1/me/storefront it returns a 403 error "Invalid authentication". I can't seem to figure out what's causing this as I'm using the user token generated from MusicKit, I also test the developer token and it works on non-user specific api end points, so it's a correct developer token. Are user tokens generated by the MusicKit swift code only able to be used in MusicKit calls in the app? Also when making a status request through MusicKit I get "MusicAuthorizationStatus.authorized(musicUserToken: null)" which seems strange as I would assume the token that's returned would be included in the status if it's including the parameter musicUserToken. The account being connected is on a 1 month free trial at the moment if that makes a difference.
Posted
by
Post not yet marked as solved
0 Replies
301 Views
I fetch user recommendations using the dedicated endpoint: var requestURLComponents = URLComponents() requestURLComponents.scheme = "https" requestURLComponents.host = "api.music.apple.com" requestURLComponents.path = "/v1/me/recommendations" guard let url = requestURLComponents.url else { return } let request = MusicDataRequest(urlRequest: URLRequest(url: url)) let response = try await request.response() Personal recommended stations (user station and "... and similar artists") were included in the result until a few weeks ago, and now I can't see them anymore. Is there a way to include the recommended stations again?
Posted
by
Post not yet marked as solved
0 Replies
491 Views
Hello Apple Developer community, I'm currently facing an issue with the integration of the Apple Music API in my application. I've followed the documentation and guidelines provided by Apple, but I'm encountering problems with authentication and parsing the Apple Music track details. Here's a summary of the issue: When making a request to fetch Apple Music track details using the provided API endpoint, I'm receiving the following error: "Error parsing Apple Music track details: The data couldn't be read because it isn't in the correct format." Additionally, the response status code is 401, indicating an unauthorized request. I have already tried the following troubleshooting steps: Verified that the MusicKit App Service is enabled in my app's App ID configuration. Confirmed that the bundle identifier used in the app matches the one in the App ID configuration. Ensured that I'm signed in with a valid Apple ID in the simulator and device I'm testing. Despite these efforts, the issue persists. I believe I have followed the correct procedures for automatic developer token generation, but there might be something missing or misconfigured. I'm seeking assistance and guidance from the Stack Overflow community on how to resolve this issue. Any insights, suggestions, or troubleshooting steps would be greatly appreciated. Thank you in advance for your help! func fetchAppleMusicTrackDetails(from mediaURL: URL, completion: @escaping (AppleMusicTrack?) -> Void) { let components = URLComponents(url: mediaURL, resolvingAgainstBaseURL: false) guard let itemID = components?.queryItems?.first(where: { $0.name == "id" })?.value else { completion(nil) return } fetchStorefront { storefront in guard let storefront = storefront else { print("storefront issue") completion(nil) return } let regex = try! NSRegularExpression(pattern: "\\s*\\(.*?\\)\\s*", options: .caseInsensitive) let trimmedStorefront = regex.stringByReplacingMatches(in: storefront, options: [], range: NSMakeRange(0, storefront.count), withTemplate: "") let encodedStorefront = trimmedStorefront.replacingOccurrences(of: " ", with: "%20") let lookupURLString = "https://api.music.apple.com/v1/catalog/\(encodedStorefront)/songs/\(itemID)" print(lookupURLString) guard let lookupURL = URL(string: lookupURLString) else { print("lookupURL issue") completion(nil) return } URLSession.shared.dataTask(with: lookupURL) { (data, response, error) in if let httpResponse = response as? HTTPURLResponse { print("Status code: \(httpResponse.statusCode)") } if let error = error { print("Error fetching Apple Music track details: \(error.localizedDescription)") completion(nil) return } guard let data = data else { completion(nil) print("no data") return } let responseString = String(data: data, encoding: .utf8) print("Response data: \(responseString ?? "No data")") do { let responseJSON = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] let results = responseJSON?["results"] as? [[String: Any]] let trackData = results?.first print(responseJSON) // Extract the necessary track information from the JSON response guard let title = trackData?["trackName"] as? String, let artist = trackData?["artistName"] as? String, let album = trackData?["collectionName"] as? String, let artworkURLString = trackData?["artworkUrl100"] as? String, let artworkURL = URL(string: artworkURLString), let trackURLString = trackData?["previewUrl"] as? String, let trackURL = URL(string: trackURLString) else { completion(nil) return } // Download the artwork image URLSession.shared.dataTask(with: artworkURL) { (artworkData, _, _) in guard let artworkData = artworkData, let artworkImage = UIImage(data: artworkData) else { completion(nil) return } let track = AppleMusicTrack(title: title, artist: artist, album: album, artwork: artworkImage, trackURL: trackURL) completion(track) }.resume() } catch { print("Error parsing Apple Music track details: \(error.localizedDescription)") completion(nil) } }.resume() } } func fetchStorefront(completion: @escaping (String?) -> Void) { SKCloudServiceController().requestStorefrontCountryCode { storefrontCountryCode, error in if let error = error { print("Error fetching storefront country code: \(error.localizedDescription)") completion(nil) return } guard let countryCode = storefrontCountryCode else { print("country code error") completion(nil) return } completion(countryCode) } }
Posted
by
Post not yet marked as solved
0 Replies
346 Views
I'm using Swift 5.0, and deploying to iOS 16. I am using the native MusicKit library for Swift. When I use the following code: let request = MusicCatalogSearchRequest( term: "dopamine - Version Francaise", types: [MusicKit.Song.self] ) let response = try await request.response() The response is completely empty. However when I search in the Music app dopamine - Version Francaise I find the song. I have found this to occur with quite a lot of songs. Am I doing something wrong here? I've tried messing around with the types by adding every type of MusicCatalogSearchable.Type, but still no luck.
Post not yet marked as solved
1 Replies
479 Views
ApplicationMusicPlayer is available on the Mac! 🎉🎉🎉 Enormous thanks to @JoeKun and the team. I've already gotten my app up and running through Catalyst, and I've successfully played music! I also got some timeouts, but that was happening on my phone a lot that day too, so maybe my local CDN was just having a bad day. I wanted to ask this question in a lab this week, but the timing didn't work out: Do you expect the experience to be the same using ApplicationMusicPlayer on a Catalyst vs a macOS target? I'm hoping to reuse much of my iPad app and go the Catalyst route, but I wanted to double check that the new support wasn't just for macOS.
Posted
by
Post marked as solved
2 Replies
1.1k Views
I've been continuing to port my app to the Mac using Catalyst, and have discovered a couple of big issues with MusicLibraryRequest which make it not particularly usable. I've submitted FBs already, but figured a forum post wouldn't hurt :) filter(matching:) functions unavailable on macOS/Catalyst - FB12301718 The first thing I noticed when building for a macOS or Catalyst target is that a couple of functions are simply not available: I'm hoping this is a bug, as these methods are crucial to being able to interact with the library. request.filter(matching: .id, equalTo:) always returns empty on Mac Catalyst - FB12301908 I have not been able to successfully retrieve an Album using a MusicLibraryRequest. The result is always empty. In the feedback, I attached a sample project that makes an unfiltered MusicLibraryRequest, then takes the first album and tries to make a new MusicLibraryRequest filtered to that album's ID. Fetching albums by ID using this method works just fine on iOS 17. Thanks again for all your work on bringing these capabilities to the Mac!
Posted
by
Post not yet marked as solved
1 Replies
682 Views
I am attempting to use MusicCatalogSearchRequest(.isrc) in order to search the catalog for info related to a song by ISRC. Issue is I get HUGE amounts of debug output in the console with the errors below. The clutter the Xcode logs to the point where I can't even view anything useful. Has anyone else seen this? Attempted to register account monitor for types client is not authorized to access: {( "com.apple.account.iTunesStore" )}
Posted
by
Post not yet marked as solved
0 Replies
802 Views
Hi, We are a funded startup developing a music festival and concert application that integrates with Apple Music. Two big features the API is missing are PUT and DELETE endpoints for tracks on a playlist. Both of these would drastically enhance the user experience on third-party apps that leverage Apple Music, specifically for editing and curating playlists. We have also noticed many errors returned as 403 when we have literally just signed in with a brand new token. We have confirmed on our end that the token is valid, fresh and can be used through other clients. As well, Apple's MusicKitJS SDK could use a bit of work. We were able to unminify and work around these issues; most of them were addressed with a simple try/catch and retry routine. We love the Apple Music API and SDK, and in general found it super easy to integrate with, setup and use. We also firmly believe Apple puts out superior products to other technology firms in the same industry. It was disappointing to see the API and SDK for Apple Music falling behind compared to other music providers who offer similar API's. We really hope Apple improves and enhances these offerings in the future. Also just wanted to give a shotout and thanks to all of the devs who make these services accessible and the integration possible. We wouldn't be here without you, and didn't want this post to come off as a rant just more of a friendly "nudge."
Posted
by