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

141 Posts
Sort by:
Post not yet marked as solved
0 Replies
426 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
4 Replies
761 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
370 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
331 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
351 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
310 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
336 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
.
Post marked as solved
1 Replies
390 Views
I am try to extract the audio file url from Shazamkit, it is deep inside the hierarchy of SHMediaItem > songs > previewAssets > url when I access the url with like this: let url = firstItem.songs[0].previewAssets?[0].url I am getting a warning like this: here is the Variable Viewer this is what I have done so far: struct MediaItems: Codable { let title: String? let subtitle: String? let shazamId: String? let appleMusicId: String? let appleMusicUrL: URL? let artworkUrl: URL? let artist: String? let matchOffset: TimeInterval? let videoUrl: URL? let webUrl: URL? let genres: [String] let isrc: String? let songs: [Song]? } extension SwiftFlutterShazamKitPlugin: SHSessionDelegate{ public func session(_ session: SHSession, didFind match: SHMatch) { let mediaItems = match.mediaItems if let firstItem = mediaItems.first { // extracting the url let url = firstItem.songs[0].previewAssets?[0].url let _shazamMedia = MediaItems( title:firstItem.title!, subtitle:firstItem.subtitle!, shazamId:firstItem.shazamID!, appleMusicId:firstItem.appleMusicID!, appleMusicUrL:firstItem.appleMusicURL!, artworkUrl:firstItem.artworkURL!, artist:firstItem.artist!, matchOffset:firstItem.matchOffset, videoUrl:firstItem.videoURL!, webUrl:firstItem.webURL!, genres:firstItem.genres, isrc:firstItem.isrc!, songs:firstItem.songs ) do { let jsonData = try JSONEncoder().encode([_shazamMedia]) let jsonString = String(data: jsonData, encoding: .utf8)! self.callbackChannel?.invokeMethod("matchFound", arguments: jsonString) } catch { callbackChannel?.invokeMethod("didHasError", arguments: "Error when trying to format data, please try again") } } }
Posted Last updated
.
Post not yet marked as solved
2 Replies
448 Views
Hi! I've been working on a project in python that pulls in a bunch of my personal apple music playback history and library, etc. I can't find a single good/functional example on how to pull the Music User Token via the android method or MusicKit JS (web) - I've spent a lot of hours on this today, and no permutation of existing examples/documentation has worked. Any guidance would be much appreciated!! If you have a web app that pulls the music user token, I just need help understanding how to get to the token itself. Thank you!
Posted Last updated
.
Post not yet marked as solved
0 Replies
341 Views
I'm writing an Android app that uses the Apple MusicKit SDK for Android. I am trying to understand how to handle the Apple Music user token, once I got it from authentication flow. I don't know when the token will expire, it is not a regular jwt token, so I cannot check the expiration date. And I don't want to run the auth flow on every app run, it will be annoying for the users. Any guidance on how to handle and invalidate apple music user tokens?
Posted
by weeto.
Last updated
.
Post not yet marked as solved
1 Replies
303 Views
I have downloaded the official Apple MusicKit SDK for Android and integrated 2 AARs it has in my app (musickitauth-release-1.1.2.aar and mediaplayback-release-1.1.1.aar). When I try to build my app I'm getting an error: Manifest merger failed : android:exported needs to be explicitly specified for element <activity#com.apple.android.sdk.authentication.SDKUriHandlerActivity>. Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. Which makes sense, since when I look into the AAR's AndroidManifest.xml I see that this is missing in SDKUriHandlerActivity. Can this be fixed?
Posted
by weeto.
Last updated
.
Post not yet marked as solved
0 Replies
457 Views
I’m using the new ApplicationMusicPlayer support on macOS 14 and playing items from my Apple Music library. I wanted to play this music from my app to an AirPlay destination so i added an AVRoutePickerView. However, selecting any destination via this view doesn’t make a difference to the playback. It continues to play on my mac speakers no matter which airplay destination i choose. Also submitted as FB13521393.
Posted
by joekw.
Last updated
.
Post not yet marked as solved
0 Replies
240 Views
When making a library sectioned request, some MusicLibraryRequestable types used result in an MusicKit.MusicLibraryRequestError being thrown. When a Playlist is used as the MusicLibrarySectionRequestable type, no other MusicLibraryRequestable type than Track can be used for the request. For others, Artist & Genre cannot be used. Is there a way to work around this issue? The (seemingly) equivalent functionality in MediaPlayer (MPMediaQuery and MPMediaGrouping) was very consistent and reliable. Full error info: MusicKit.MusicLibraryRequestError.invalidType, The operation couldn’t be completed. (MusicKit.MusicLibraryRequestError error 1.) Device and OS: iPhone 13 Pro, iOS 17.2.1
Posted
by ezenwa.
Last updated
.
Post not yet marked as solved
0 Replies
370 Views
Hello Apple Community, First, I'm asking this on the holidays, so happy holidays. Now I have some "fun coding time" and can do it because I have some holiday time. I'm new to this area and would greatly appreciate your expertise and guidance. Have mercy. I'm attempting to develop a simple application on my Mac OS to browse my playlists. However, I've encountered a few roadblocks that I struggle to navigate. I understand I need to implement two-factor authentication to access my playlists, for which an OAuth setup is required. This involves obtaining an Apple ID and a service ID and dealing with other complex elements. One particular challenge I'm facing is with the redirect URI in the OAuth process. It seems that it needs to be a valid domain, and I'm unsure if using a local server address like https://localhost:5000 would work. My goal is to create a basic Flask application that can interact with Apple's web authentication system, but I'm uncertain about the feasibility of this approach, given the domain restrictions. I would appreciate any advice or step-by-step guidance on the following points. What would be the simplest way to create an application (Swift, Python, or JavaScript) that can authenticate and enable browsing through my playlists? Any insights, tips, or examples you could share would be immensely helpful. I am eager to learn and look forward to your valuable suggestions. Anything step-by-step would be great, but I like to dream. Thank you so much for your time and assistance.
Posted
by terkaly.
Last updated
.
Post not yet marked as solved
1 Replies
555 Views
2 Days and I am frustrated. I"ve crossed my T's and dotted my I's. Using musickit Error Attempted to register account monitor for types client is not authorized to access: {( "com.apple.account.iTunesStore" )} Offending Code var request = MusicLibraryRequest<MusicKit.Playlist>() request.sort(by: .lastPlayedDate, ascending: false) let response = try await request.response() Verified Custom IOS Target Properities Privacy - Media Library Usage Description Correct Bundle Identifier Checkbox AppServcies/Music Kit for App ID Please help! 2 days of racking my brain, just can't get passed error MusicKit does ask me to authorize Other code works let request = MusicRecentlyPlayedContainerRequest() let response = try await request.response() See Image
Posted
by terkaly.
Last updated
.
Post not yet marked as solved
0 Replies
251 Views
I'm trying to test the MusicMarathon and MusicAlbums tutorial/demo apps for MusicKit and half the endpoints do not work. As an example the MusicMarathon call to MusicRecentlyPlayedContainerRequest() just returns a 401. Everything I've done seems correct. I've got a fully authorized session and I have all the development keys successfully setup. Also it's not all API's as I can access the users Library, Just none of the recommendation and search endpoints seems to be working correctly. I'm running iOS 17.2 and Xcode 15.1 I'm pretty certain this is easily repeatable by just running the demo applications from the MusicKit documentation,
Posted
by evulse.
Last updated
.
Post not yet marked as solved
0 Replies
488 Views
I want to add a small play button to play a song preview on my site. I don't want to use the embedded player because I want to style it custom. If I use the MusicKit Web library, do I need to add Apple branding legally? I don't see anywhere that says its required and I want to confirm.
Posted Last updated
.
Post not yet marked as solved
0 Replies
309 Views
I recently downloaded Apple Music for for Windows 10 and started a new music library. Then I downloaded all my purchased music albums to my computer. However, the album art is not embedded in any of the m4a files. It is stored in a separate artwork folder. I have Visual Studio 2022 and was wondering how I might go about accessing the Apple Music app using the API. I want the script to go through all my purchased music and take the album art from the artwork folder and embed it in the purchased m4a files. I found some other programs/scripts online but they are all for iTunes or for Mac. None of the old scripts will work because they don’t recognize the new Apple Music for Windows music library. I can’t go back to iTunes because Apple removed all the music options from the iTunes for Windows app. Any ideas on how to get started writing the app/script would be greatly appreciated. Can I download something from Apple to make it easy to access the API in Visual Studio 2022 for Windows?
Posted
by altmanjc.
Last updated
.