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

146 Posts
Sort by:
Post not yet marked as solved
0 Replies
277 Views
I often find when doing basic actions in MusicKit it is incredibly slow compared to Apple's Music App. I've tried different versions, devices, networks, Apple's sample code, it all throughout the last several years, and it is all the same. Does anyone else have this issue?
Posted Last updated
.
Post not yet marked as solved
7 Replies
2.9k Views
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?
Posted
by xinsight.
Last updated
.
Post not yet marked as solved
0 Replies
227 Views
I can't seem to find an album using MusicKit containing RecordLabel. I am using album.with([..., .recordLabels, ...] but I only see an empty recordLabels collection returned for every album I am trying... Is this actually available / populated through MusicKit?
Posted
by ridmaur.
Last updated
.
Post not yet marked as solved
0 Replies
254 Views
Hello, I am working on the Musickit web browser application. I have created my developer token as mentioned in the documentation. When I call the authorize() method to authenticate, I get the Apple Music pop up as expected. However, after entering the user credentials and "allowing" access, I get the following error: POST https://play.itunes.apple.com/WebObjects/MZPlay.woa/wa/webPlayerLogout 403 (Forbidden) musickit.js:28 Uncaught (in promise) AUTHORIZATION_ERROR: Unauthorized at https://js-cdn.music.apple.com/musickit/v3/musickit.js:28:269512 at Generator.next () at asyncGeneratorStep$u (https://js-cdn.music.apple.com/musickit/v3/musickit.js:28:266594) at _next (https://js-cdn.music.apple.com/musickit/v3/musickit.js:28:266821) I am using an user account with paid subscription to Apple Music. With the JWT created, I am able to make API calls and receive the response for requests that do that need the userToken. I am currently stuck at this step and would like some help to root cause this issue.
Posted
by mismatcha.
Last updated
.
Post not yet marked as solved
11 Replies
2.6k Views
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?
Posted
by benzgrant.
Last updated
.
Post not yet marked as solved
0 Replies
244 Views
Hi! For a couple of days and only for some users, we are getting this error message on this endpoint: https://api.music.apple.com/v1/me/library/playlists?limit=100 {"id":"6NT5LBXIZW65K2G3L6QY3WWYAA","title":"Upstream Service Error","detail":"Error fetching library content","status":"500","code":"50001"} Any idea?
Posted Last updated
.
Post not yet marked as solved
0 Replies
296 Views
I am working on a radio app. This is the first time and I have a problem with lock Screen Audio Card. According to docs It looks ok but could you please check why I can not display Audio Now Playing Card on lock Screen. 2 Code samples, 1. Now Playing and 2. Logic of current song and Album art. 1. Now Playing // Create a dictionary to hold the now playing information var nowPlayingInfo: [String: Any] = [:] // Set the title of the current song nowPlayingInfo[MPMediaItemPropertyTitle] = currentSong // If album art URL is available, fetch the image asynchronously if let albumArtUrl = albumArtUrl { URLSession.shared.dataTask(with: albumArtUrl) { data, _, error in if let data = data, let image = UIImage(data: data) { // Create artwork object let artwork = MPMediaItemArtwork(boundsSize: image.size) { _ in image } // Update now playing info with artwork on the main queue DispatchQueue.main.async { nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo } } else { // If there's an error fetching the album art, set now playing info without artwork MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo print("Error retrieving album art data:", error?.localizedDescription ?? "Unknown error") } }.resume() } else { // If album art URL is not available, set now playing info without artwork MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo } } 2. Current Song, Album Art Logic let parts = currentSong.split(separator: "-", maxSplits: 1, omittingEmptySubsequences: true).map { $0.trimmingCharacters(in: .whitespaces) } let titleWithExtra = parts.count > 1 ? parts[1] : "" let title = titleWithExtra.components(separatedBy: " (").first ?? titleWithExtra return title } func updateSongInfo() { let url = URL(string: "https://live.heartfm.com.tr/listen/heart_fm/currentsong")! URLSession.shared.dataTask(with: url) { data, response, error in if let data = data, let songString = String(data: data, encoding: .utf8) { DispatchQueue.main.async { self.currentSong = songString.trimmingCharacters(in: .whitespacesAndNewlines) self.updateAlbumArtUrl(song: self.currentSong) } } }.resume() } private func updateAlbumArtUrl(song: String) { let parts = song.split(separator: "-", maxSplits: 1, omittingEmptySubsequences: true).map { $0.trimmingCharacters(in: .whitespaces) } let artist = parts.first ?? "" let titleWithExtra = parts.count > 1 ? parts[1] : "" let title = titleWithExtra.components(separatedBy: " (").first ?? titleWithExtra let artistAndTitle = artist.isEmpty || title.isEmpty ? song : "\(artist) - \(title)" let encodedArtistAndTitle = artistAndTitle.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? artistAndTitle albumArtUrl = URL(string: "https://www.heartfm.com.tr/ArtCover/\(encodedArtistAndTitle).jpg") }
Posted
by lcyzkn.
Last updated
.
Post not yet marked as solved
0 Replies
241 Views
I am currently experimenting with the MusicKit API, specifically if/how it could replace iTunesLibrary on macOS and MediaPlayer on iOS. My question is specifically about DRM-free tracks that the user has available locally (e.g. purchased, matched or uploaded tracks): Is there a way to access the on-disk URL of locally available and DRM-free tracks? In the iTunesLibrary framework on macOS there is ITLibMediaItem.location and on iOS I can get this path via MPMediaItem.assetURL, but MusicKit's Song.url seems to be nil for all of these tracks in my tests.
Posted
by fwcd.
Last updated
.
Post not yet marked as solved
0 Replies
199 Views
Hey there, I have been trying to add the ability for a user to edit the playback rate of a song in their Apple Music library to my application. I have found that whenever the playback rate is changed, the music pausing for about half a second. I was wondering what the cause of this issue is and if there is anyway around it. For context I am using the SystemMusicPlayer from MusicKit.
Posted
by rogutkuba.
Last updated
.
Post not yet marked as solved
0 Replies
266 Views
I can not find an album where isCompilation is true, even when the album clearly consists of "songs by various artists". For example: Album( id: "567979803", title: "Earth's Answer", artistName: "Brian Keane, Deuter, James Newton, ,...many more", isCompilation: false The compilation checkbox for this album in the Apple Music Catalog Get Info dialog is also not checked. Is this field NEVER SET in the catalog or the MusicKit API? If there IS an album where isCompilation is true, I'd like its ID to use for a test case. If not, can this be added to the API?
Posted
by ronzo99.
Last updated
.
Post not yet marked as solved
1 Replies
328 Views
Is there a way to retrieve a list of all the favorited artists for a given user via the Apple Music API? I see endpoints for playback history and resources added to the library. But I want to retrieve the full list of favorited artists for the given user and I don't see any obvious choices in the documentation. Thanks in advance!
Posted Last updated
.
Post not yet marked as solved
0 Replies
388 Views
Running in a Mac (Catalyst) target or Apple Silicon (designed for iPad). Just accessing the playbackStoreID from the MPMediaItem shows this error in the console: -[ITMediaItem valueForMPMediaEntityProperty:]: Unhandled MPMediaEntityProperty subscriptionStoreItemAdamID. The value returned is always “”. This works as expected on iOS and iPadOS, returning a valid playbackStoreID. import SwiftUI import MediaPlayer @main struct PSIDDemoApp: App { var body: some Scene { WindowGroup { Text("playbackStoreID demo") .task { let authResult = await MPMediaLibrary.requestAuthorization() if authResult == .authorized { if let item = MPMediaQuery.songs().items?.first { let persistentID = item.persistentID let playbackStoreID = item.playbackStoreID // <--- Here print("Item \(persistentID), \(playbackStoreID)") } } } } } } Xcode 15.1, also tested with Xcode 15.3 beta 2. MacOS Sonoma 14.3.1 FB13607631
Posted
by gbuela.
Last updated
.
Post not yet marked as solved
3 Replies
723 Views
I'm building a UIKit app that reads user's Apple Music library and displays it. In MusicKit there is the Artwork structure which I need to use to display artwork images in the app. Since I'm not using SwiftUI I cannot use the ArtworkImage view that is recommended way of displaying those images but the Artwork structure has a method that returns url for the image which can be used to read the image. The way I have it setup is really simple: extension MusicKit.Song { func imageURL(for cgSize: CGSize) -> URL? { return artwork?.url( width: Int(cgSize.width), height: Int(cgSize.height) ) } func localImage(for cgSize: CGSize) -> UIImage? { guard let url = imageURL(for: cgSize), url.scheme == "musicKit", let data = try? Data(contentsOf: url) else { return nil } return .init(data: data) } } Now, everytime I access .artwork property (so a lot of times) the main thread gets blocked and the console output gets bombared with messages like these: 2023-07-26 11:49:47.317195+0200 Plum[998:297199] [Artwork] Failed to create color analysis for artwork: <MPMediaLibraryArtwork: 0x289591590> with error; Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.mediaartworkd.xpc was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.mediaartworkd.xpc was invalidated: failed at lookup with error 159 - Sandbox restriction.} 2023-07-26 11:49:47.317262+0200 Plum[998:297199] [Artwork] Failed to create color analysis for artwork: file:///var/mobile/Media/iTunes_Control/iTunes/Artwork/Originals/4b/48d7b8d349d2de858413ae4561b6ba1b294dc7 2023-07-26 11:49:47.323099+0200 Plum[998:297013] [Plum] IIOImageWriteSession:121: cannot create: '/var/mobile/Media/iTunes_Control/iTunes/Artwork/Caches/320x320/4b/48d7b8d349d2de858413ae4561b6ba1b294dc7.sb-f9c7943d-6ciLNp'error = 1 (Operation not permitted) My guess is that the most performance-heavy task here is performing the color analysis for each artwork but IMO the property backgroundColor should not be a stored property if that's the case. I am not planning to use it anywhere and if so it should be a computed async property so it doesn't block the caller. I know I can move the call to a background thread and that fixes the issue of blocking main thread but still the loading times for each artwork are terribly slow and that impacts the UX. SwiftUI's ArtworkImage loads the artworks much quicker and without the errors so there must be a better way to do it.
Posted
by wiencheck.
Last updated
.
Post not yet marked as solved
0 Replies
340 Views
My app is consistently crashing for a specific user on 14.3 (iMac (24-inch, M1, 2021) when their library is being retrieved in full. User says they have 36k+ songs in their library which includes purchased music. This is the code making the call: var request = MusicLibraryRequest<Album>() request.limit = 10000 let response = try await request.response() I’m aware of a similar (?) crash FB13094022 (https://forums.developer.apple.com/forums/thread/736717) that was claim fixed for 14.2. Not sure if this is a separate issue or linked. I’ve submitted new FB13573268 for it. CrashReporter Key: 0455323d871db6008623d9288ecee16c676248c6 Hardware Model: iMac21,1 Process: Music Flow Identifier: com.third.musicflow Version: 1.2 Role: Foreground OS Version: Mac OS 14.3 NSInternalInconsistencyException: No identifiers for model class: MPModelSong from source: (null) 0 CoreFoundation +0xf2530 __exceptionPreprocess 1 libobjc.A.dylib +0x19eb0 objc_exception_throw 2 Foundation +0x10f398 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] 3 MediaPlayer +0xd59f0 -[MPBaseEntityTranslator _objectForPropertySet:source:context:] 4 MediaPlayer +0xd574c -[MPBaseEntityTranslator _objectForRelationshipKey:propertySet:source:context:] 5 MediaPlayer +0xd5cd4 __63-[MPBaseEntityTranslator _objectForPropertySet:source:context:]_block_invoke_2 6 CoreFoundation +0x40428 __NSDICTIONARY_IS_CALLING_OUT_TO_A_BLOCK__ 7 CoreFoundation +0x402f0 -[__NSDictionaryI enumerateKeysAndObjectsWithOptions:usingBlock:] 8 MediaPlayer +0xd5c1c __63-[MPBaseEntityTranslator _objectForPropertySet:source:context:]_block_invoke 9 MediaPlayer +0x11296c -[MPModelObject initWithIdentifiers:block:] 10 MediaPlayer +0xd593c -[MPBaseEntityTranslator _objectForPropertySet:source:context:] 11 MediaPlayer +0xd66c4 -[MPBaseEntityTranslator objectForPropertySet:source:context:] 12 MediaPlayer +0x1a7744 __47-[MPModeliTunesLibraryRequestOperation execute]_block_invoke 13 iTunesLibrary +0x16d84 0x1b4e1cd84 (0x1b4e1cd30 + 84) 14 CoreFoundation +0x5dec0 __invoking___ 15 CoreFoundation +0x5dd38 -[NSInvocation invoke] 16 Foundation +0x1e874 __NSXPCCONNECTION_IS_CALLING_OUT_TO_REPLY_BLOCK__ 17 Foundation +0x1cef4 -[NSXPCConnection _decodeAndInvokeReplyBlockWithEvent:sequence:replyInfo:] 18 Foundation +0x1c850 __88-[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:]_block_invoke_3 19 libxpc.dylib +0x10020 _xpc_connection_reply_callout 20 libxpc.dylib +0xff18 _xpc_connection_call_reply_async 21 libdispatch.dylib +0x398c _dispatch_client_callout3 22 libdispatch.dylib +0x21384 _dispatch_mach_msg_async_reply_invoke 23 libdispatch.dylib +0xad24 _dispatch_lane_serial_drain 24 libdispatch.dylib +0xba04 _dispatch_lane_invoke 25 libdispatch.dylib +0x16618 _dispatch_root_queue_drain_deferred_wlh 26 libdispatch.dylib +0x15e8c _dispatch_workloop_worker_thread 27 libsystem_pthread.dylib +0x3110 _pthread_wqthread 28 libsystem_pthread.dylib +0x1e2c start_wqthread
Posted
by Bardi.
Last updated
.
Post not yet marked as solved
0 Replies
307 Views
Not sure when it happened but I can no longer play explicit songs in my app using MK v3. I've turned off restrictions/made sure i have access to explicit in... My phone (Screen Time) My computer (Screen Time) My iPad (Screen Time) music.apple.com (Settings) and I still get this error when I try to play a song in console. `CONTENT_RESTRICTED: Content restricted at set isRestricted (https://js-cdn.music.apple.com/musickit/v3/musickit.js:28:296791) at SerialPlaybackController._prepareQueue (https://js-cdn.music.apple.com/musickit/v3/musickit.js:28:318357) at SerialPlaybackController._prepareQueue (https://js-cdn.music.apple.com/musickit/v3/musickit.js:28:359408) at set queue (https://js-cdn.music.apple.com/musickit/v3/musickit.js:28:308934) at https://js-cdn.music.apple.com/musickit/v3/musickit.js:28:357429 at Generator.next (<anonymous>) at asyncGeneratorStep$j (https://js-cdn.music.apple.com/musickit/v3/musickit.js:28:351481) at _next (https://js-cdn.music.apple.com/musickit/v3/musickit.js:28:351708)`
Posted
by nyc2phx.
Last updated
.
Post not yet marked as solved
0 Replies
329 Views
I am trying to retrieve same information about a song as is available on the music.apple.com page (see screenshot). It seems neither MusicKit and/or Apple Music API's deliver that depth of information. For example, the names listed for Production and Techniques. Am I correct?
Posted
by ridmaur.
Last updated
.
Post not yet marked as solved
0 Replies
290 Views
Is it possible using MusicKit API's to access the About information displayed on an artist page in Apple Music? I hoped Artist.editiorialNotes would give me the information but there is scarce information in there. Even for Taylor Swift, only editorialNotes.short displays brief info: "The genre-defying singer-songwriter is the voice of a generation." If currently not possible, are there plans for it in the future? Also, with the above in mind, and never seen any editorialNotes for a song, is it safe to assume editorialNotes are mainly used for albums?
Posted
by ridmaur.
Last updated
.
Post not yet marked as solved
1 Replies
316 Views
struct AlbumDetails : Hashable { let artistId: String? } func fetchAlbumDetails(upc: String) async throws -> AlbumDetails { let request = MusicCatalogResourceRequest<Album>(matching: \.upc, equalTo: upc) let response = try await request.response() guard let album = response.items.first else { throw NSError(domain: "AlbumNotFound", code: 0, userInfo: nil) } do { let artistID = try await fetchAlbumDetails(upc: upc) print("Artist ID: \(artistID)") } catch { print("Error fetching artist ID: \(error)") } return AlbumDetails(artistId: album.artists?.first?.id) with this function, i can return nearly everything except the artist ID so i know its not a problem with the request but I know there has to be a way to get the artistID, there has too. If anyone has a solution to this I would reallly appricate it
Posted
by loudiBird.
Last updated
.