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

145 Posts
Sort by:
Post not yet marked as solved
4 Replies
11k Views
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
Posted
by
Post not yet marked as solved
16 Replies
16k Views
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!
Posted
by
Post marked as solved
2 Replies
857 Views
While trying to login to the Apple MusicKitJS .authorize method I get an error that says:Problem ConnectingThere may be a network issue.After logging in, but before I click accept to the application.
Posted
by
Post not yet marked as solved
1 Replies
607 Views
I'm trying to interface the Apple Musickit SDK to my android app. I'm facing a lot of delay at the start of a song which is heavily going to affect the user experience. To overcome this delay, I tried to add a few tracks(queueAdd1 is a apple music id) to the queue by doing the following-List Q1 = playerController.getQueueItems(); boolean canAppend = playerController.canAppendToPlaybackQueue(); queueProviderBuilder.items(MediaItemType.SONG,queueAdd1); playerController.addQueueItems(queueProviderBuilder.build(); PlaybackQueueInsertionType.INSERTION_TYPE_AFTER_CURRENT_ITEM); List Q2 = playerController.getQueueItems();But these songs are not getting added to the queue for some reason. Do I need to call playercontroller.prepare() also on this to add tracks to the queue?Or is there a better way to load tracks faster?
Posted
by
Post not yet marked as solved
1 Replies
3.5k Views
Would it be possible to get volume control in the Android SDK for platforms that share STREAM_MUSIC with ExoPlayer?
Posted
by
Post not yet marked as solved
6 Replies
3.9k Views
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]
Posted
by
Post not yet marked as solved
4 Replies
2.5k Views
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>
Posted
by
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
Post not yet marked as solved
3 Replies
1.4k Views
I'd like to be able to monitor what is queued and what is currently playing in MusicKit's ApplicationMusicPlayer. Use cases: Show a "playing" indicator on the current track in a list. Show a "now playing" bar with song title, album, and artist. Is this possible?
Posted
by
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
Post marked as solved
11 Replies
3.6k Views
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?
Posted
by
Post not yet marked as solved
2 Replies
1.8k Views
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
Posted
by
Post not yet marked as solved
24 Replies
7.2k Views
Just wondering if anyone else is having issues with currentPlaybackRate in release version of iOS 15.4? In my particular case this is using MPMusicPlayerController.applicationQueuePlayer. I've always had issues controlling this property reliably but from what I can see it is now completely non-operational in 15.4. I've isolated this behavior in a trivial project, and will file a radar, but hoping others may have some insight first. FWIW- This is my trivial test case: class ViewController: UIViewController {     lazy var player: MPMusicPlayerApplicationController = {         let player = MPMusicPlayerController.applicationQueuePlayer         player.repeatMode = .none         player.shuffleMode = .off         player.beginGeneratingPlaybackNotifications()         return player     }()     override func viewDidLoad() {         super.viewDidLoad()         NotificationCenter.default.addObserver(forName: .MPMusicPlayerControllerPlaybackStateDidChange, object: nil, queue: .main) { [weak self] notification in             guard let notificationPlayer = notification.object as? MPMusicPlayerApplicationController,                   notificationPlayer === self?.player else {                 return             }                          debugPrint("Player state now: \(notificationPlayer.playbackState)")         }     }     @IBAction func goAction(_ sender: Any) {         guard let item = MPMediaQuery.songs().items?.randomElement() else {             debugPrint("Unable to access media items")             return         }         debugPrint("Now playing item: \(item.title ?? "")")         player.setQueue(with: [item.playbackStoreID])         player.prepareToPlay() { error in             guard error == nil else {                 debugPrint("Player error: \(error!.localizedDescription)")                 return             }             DispatchQueue.main.async { [weak self] in                 self?.player.play()             }         }     } @IBAction func slowAction(_ sender: Any) {         debugPrint("Setting currentPlaybackRate to 0.5")         player.currentPlaybackRate = 0.5         checkPlaybackRate()     } @IBAction func fastAction(_ sender: Any) {         debugPrint("Setting currentPlaybackRate to 1.5")         player.currentPlaybackRate = 1.5         checkPlaybackRate()     } func checkPlaybackRate(afterSeconds delay: TimeInterval = 1.0) {         DispatchQueue.main.asyncAfter(deadline: .now() + delay) {             debugPrint("After \(delay) seconds currentPlaybackRate now: \(self.player.currentPlaybackRate)")         }     } } Typical console output: "Now playing item: I Know You Know" "Player state now: MPMusicPlaybackState(rawValue: 2)" "Player state now: MPMusicPlaybackState(rawValue: 1)" "Setting currentPlaybackRate to 1.5" "After 1.0 seconds currentPlaybackRate now: 1.0" "Setting currentPlaybackRate to 0.5" "After 1.0 seconds currentPlaybackRate now: 1.0"
Posted
by
Post not yet marked as solved
4 Replies
1.5k Views
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
Posted
by
Post marked as solved
2 Replies
1.6k Views
Hey there Apple Music team! I'm excited to dig into the sessions coming up this week, and what I've seen so far from the developer documentation diffs looks great: audio quality, artist images, and a way to interface with a user's music library in MusicKit. Love it! The thing at the very top of my WWDC wishlist this year was macOS/Mac Catalyst support for the ApplicationMusicPlayer class. I just got finished installing Ventura and Xcode 14, and sadly it looks like the support story is the same as on Big Sur. No API availability on macOS, and an available Mac Catalyst API that ultimately results in the same error from a feedback I submitted on Big Sur: FB9851840 The connection to service named com.apple.Music.MPMusicPlayerApplicationControllerInternal was invalidated: failed at lookup with error 3 - No such process. Is that the end of the story on Ventura, or is there a chance support might be added in a later beta? Is there any additional detail at all that can be shared? I field several requests a week asking if/when my app is coming to the Mac, and I would really love to be able to make that happen. If there is anything at all I can do to test and help overcome the engineering challenges alluded to in the past, I am ready, willing, and able! In any case, thanks for the great work, and I'm looking forward to spending time with the new stuff this summer.
Posted
by
Post not yet marked as solved
10 Replies
2.4k Views
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?
Posted
by
Post not yet marked as solved
8 Replies
2.1k Views
Hi there, tl;dr: What's the best way to get all tracks (with catalog IDs) from a playlist that has more than 100 tracks, using MusicLibraryRequest. I'm doing something dumb, not understanding something, and possibly both. I've got an existing, kinda okay function that uses the MusicDataRequest and the Apple Music API to fetch all tracks from a playlist, with pagination like this: func getTracksFromAppleMusicLibraryPlaylist(playlist: AppleMusicPlaylist) async throws -> [MusicKit.Track]? {     var tracksToReturn: [MusicKit.Track] = []     var libraryTracks: [AppleMusicLibraryTrack] = []     @Sendable     func fetchTracks(playlist: AppleMusicPlaylist, offset: Int) async -> AppleMusicPlaylistFetchResponse? {         do {             let playlistId = playlist.id             var playlistRequestURLComponents = URLComponents()             playlistRequestURLComponents.scheme = "https"             playlistRequestURLComponents.host = "api.music.apple.com"             playlistRequestURLComponents.path = "/v1/me/library/playlists/\(playlistId)/tracks"             playlistRequestURLComponents.queryItems = [                 URLQueryItem(name: "include", value: "catalog"),                 URLQueryItem(name: "limit", value: "100"),                 URLQueryItem(name: "offset", value: String(offset)),             ]             if let playlistRequestURL = playlistRequestURLComponents.url {                 let playlistRequest = MusicDataRequest(urlRequest: URLRequest(url: playlistRequestURL))                 let playlistResponse = try await playlistRequest.response()                 let decoder = JSONDecoder()                 // print("Get Tracks Dump")                 // print(String(data: playlistResponse.data, encoding: .utf8)!)                            let response = try decoder.decode(AppleMusicPlaylistFetchResponse.self, from: playlistResponse.data)                 return response             } else {                 print("Bad URL!")             }         } catch {             print(error)         }         return nil     }     Logger.log(.info, "Fetching inital tracks from \(playlist.attributes.name)")     if let response = await fetchTracks(playlist: playlist, offset: 0) {         if let items = response.data {             libraryTracks = items         }         if let totalItemCount = response.meta?.total {             Logger.log(.info, "There are \(totalItemCount) track(s) in \(playlist.attributes.name)")             if totalItemCount > 100 {                 let remainingItems = (totalItemCount - 100)                 let calls = remainingItems <= 100 ? 1 : (totalItemCount - 100) / 100                 Logger.log(.info, "Total items: \(totalItemCount)")                 Logger.log(.info, "Remaining items: \(remainingItems)")                 Logger.log(.info, "Calls: \(calls)")                 await withTaskGroup(of: [AppleMusicLibraryTrack]?.self) { group in                     for offset in stride(from: 100, to: calls * 100, by: 100) {                         Logger.log(.info, "Fetching additional tracks from \(playlist.attributes.name) with offset of \(offset)")                         group.addTask {                             if let response = await fetchTracks(playlist: playlist, offset: offset) {                                 if let items = response.data {                                     return items                                 }                             }                             return nil                         }                     }                     for await (fetchedTracks) in group {                         if let tracks = fetchedTracks {                             libraryTracks.append(contentsOf: tracks)                         }                     }                 }             }         }     } // props to @JoeKun for this bit of magic     Logger.log(.info, "Matching library playlist tracks with catalog tracks...")     for (i, track) in libraryTracks.enumerated() {         if let correspondingCatalogTrack = track.relationships?.catalog?.first {             tracksToReturn.append(correspondingCatalogTrack)             print("\(i) => \(track.id) corresponds to catalog track with ID: \(correspondingCatalogTrack.id).")         } else {             Logger.log(.warning, "\(i) => \(track.id) doesn't have any corresponding catalog track.")         }     }     if tracksToReturn.count == 0 {         return nil     }     return tracksToReturn } While not the most elegant, it gets the job done, and it's kinda quick due to the use of withTaskGroup .esp with playlists containing more than 100 songs/tracks. Regardless, I'm kinda stuck, trying to do something similar with the new MusicLibraryReqeust in iOS 16. The only way I can think of to get tracks from a playlist, using MusicLibraryRequest, having read the new docs, is like this: @available(iOS 16.0, *) func getAllTracksFromHugePlaylist(id: MusicItemID) async throws -> [MusicKit.Track]? {     do {         var request = MusicLibraryRequest<MusicKit.Playlist>()         request.filter(matching: \.id, equalTo: id)         let response = try await request.response()         if response.items.count > 0 {             if let tracks = try await response.items[0].with(.tracks, preferredSource: .catalog).tracks {                 Logger.log(.info, "Playlist track count: \(tracks.count)")                 return tracks.compactMap{$0}             }         }     } catch {         Logger.log(.error, "Could not: \(error)")     }     return nil } The problem with this is that .with seems to be capped at 100 songs/tracks, and I can't see any way to change that. Knowing that, I can't seem to tell MusicLibraryRequest that I want the tracks of the playlist with the initial request, where before I could use request.properties = .tracks, which I could then paginate if available. Any help setting me on the right course would be greatly appreciated.
Posted
by
Post not yet marked as solved
3 Replies
809 Views
Android Music SDK Authentication always shows Install AppMusic App even though AppMusic App is already installed! when targetSdkVersion 29 works fine and shows links to Apple Music but using targetSdkVersion 30 always shows Install AppMusic App even though AppMusic App is already installed! Apple developer, please check this problem device : Pixel 6 Android os version : 12
Posted
by