I tried to use smart playlist to get all liked songs. But Smart playlists are not returned from Library Playlists endpoint https://api.music.apple.com/v1/me/library/playlists — only the regular playlists are returned.Is there a way to fetch user's smart playlists?If not is there a way to fetch liked songs? Currently I have to load ALL songs and the ratings for all of them, then manually filter. It takes ridiculous amount of time, especially because page size is limited to 100. Btw, is there a way to increase it?
Apple Music API
RSS for tagApple Music API integrates streaming music with Apple Music content.
Posts under Apple Music API tag
72 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
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]
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();
		music.player.play();
		music.authorize().then(function() {
				music.player.play();
		});
		music.authorize().then(function() {
				 music.api.library.albums.then(function(cloudAlbums) {
							// user's cloudAlbums
				});
		});
</script>
</html>
Hello,
I am wondering how one can play music videos (with the actual video playing) with the ApplicationMusicPlayer using MusicKit for Swift?
There is not much documentation on this, so any help would be appreciated.
I want to get playCount of an user library song from Apple Music API. Or is there any other way that I can access that how many times they have played a specific song.
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
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
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.
In my Developer account under Certificates, Identifiers & Profiles --> 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?
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!
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></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?
Is there a way to get the user name after login if I use Apple Music Kit JS or using the APIs?
Or can I use the music token from Apple Music kit JS with Apple Sign In to get a user name?
Greetings
I have two apple ID's. On my iPhone (16.x) I have Apple Music on with no issues.
On the beta I am not given a choice of adding another Apple ID for Apple Music.
In Settings go to Apple ID and tap on Subscriptions. I only see the current Apple ID using the OS-17 beta release
Has anyone seen this?
Hello,
I have an app published on AppStore which relies on MusicKit's functionality to retrieve results of MusicCatalogSearchRequest even when a user doesn't have an Apple Music subscription. (As per other sources and this thread, this is expected to work normally for users without the subscription.)
The app used to work fine for months, yet today all the devices I tested on failed to execute the request (both AppStore and dev versions), resulting in the following log:
2023-07-27 23:45:16.036271+0200 Lisyn[6288:3156868] [DataRequesting] Updated user token cache with new error.
2023-07-27 23:45:16.043294+0200 Lisyn[6288:3156868] [DataRequesting] Failed retrieving user token: Error Domain=ICError Code=-8101 "Failed to fetch music user token with Unauthorized (401) status code. Account does not have an active Apple Music Subscription." UserInfo={NSDebugDescription=Failed to fetch music user token with Unauthorized (401) status code. Account does not have an active Apple Music Subscription.}. Throwing .userTokenRequestFailed.
2023-07-27 23:45:16.043413+0200 Lisyn[6288:3156868] [DataRequesting] Failed refreshing user token for MusicDataRequest.Context(
url: "https://api.music.apple.com/v1/catalog/it/search?term=B&l=en-GB&types=songs&limit=25&omit%5Bresource%5D=autos",
currentRetryCounts: [.userTokenInvalid: 1],
activeRetryContext: RetryContext(
reason: .userTokenInvalid,
previousTokens: .personalizedTokens(
developerToken: "some token",
userToken: "some other token"
)
)
). Error = .userTokenRequestFailed.
I am using automatic token generation and make requests via MusicKit:
func searchMusic(searchText: String) async throws -> [PlaybackStoreID] {
return try await throttler.schedule {
var request = MusicCatalogSearchRequest(term: searchText, types: [Song.self])
request.limit = 25
return try await request.response().songs.map(\.id.rawValue)
}
}
None of the certificate/identifier settings, nor the code related to the issue has been touched between when it was working and now. Also, live versions stopped working as well, so I am sure this isn't related.
Is this a temporary issue? Should I roll out a fix using non-automatic token generation?
Thank you!
I'm trying to pull library songs, playlist and artist from authorized user. The API gives me data in alphabetical order and there's no timestamp in the response, is it possible to fetch data with the most recent ones first?
It is very difficult to pull all the data and filter ourselves, is it possible to fetch only the first 30-60 most recent ones?
We are using the following endpoint to add songs to a user's library playlist:
https://developer.apple.com/documentation/applemusicapi/add_tracks_to_a_library_playlist
However, it looks like it is currently only possible to add tracks to the end of a playlist, and there is no way of re-ordering the tracks either. It would be great if we were able to pass an index of the position where the object should be added within the playlist, or if that's too complicated, then at least have a param that allows to add tracks to the beginning of the playlist.
Adding new tracks at the end of a playlists that already has a lot of songs just isn't effective as they won't be discovered.
I am trying to create a new playlist folder in Apple Music using MusicKit on iOS 16. However, I am receiving an Internal Service Error when sending the request.
This is the code:
let urlString = "https://api.music.apple.com/v1/me/library/playlist-folders"
let url = URL(string: urlString)!
let body = LibraryPlaylistFolderCreationRequest(
attributes: .init(
name: "test-playlist-folder"),
relationships: .init(
parent: .init(
data: [.init(id: "playlistsroot", type: "library-playlist-folders")])))
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.httpBody = try JSONEncoder().encode(body)
let request = MusicDataRequest(urlRequest: urlRequest)
let response = try await request.response()
let responseString = String(data: response.data, encoding: .utf8)
print(responseString)
When I print the request body using the following code snippet, I get the output as seen below:
let jsonBody = try JSONEncoder().encode(body)
print(String(data: jsonBody, encoding: .utf8))
Output of the above snippet:
Optional("{\"attributes\":{\"name\":\"test-playlist-folder\"},\"relationships\":{\"parent\":{\"data\":[{\"id\":\"playlistsroot\",\"type\":\"library-playlist-folders\"}]}}}")
Which should conform to the JSON scheme provided in the docs: https://developer.apple.com/documentation/applemusicapi/libraryplaylistfoldercreationrequest
And this is the error output:
[DataRequesting] Failed to perform MusicDataRequest.Context(
url: "https://api.music.apple.com/v1/me/library/playlist-folders",
currentRetryCounts: [.other: 1]
) with MusicDataRequest.Error(
status: 500,
code: 50000,
title: "Internal Service Error",
detailText: "",
id: "VK23VIZ6AAM5IVP4GIFQ6VXPLU",
originalResponse: MusicDataResponse(
data: 111 bytes,
urlResponse: <NSHTTPURLResponse: 0x000000028042b0c0>
)
).
After a lot of trial and error, I don't think I know what the underlying issue is. Is MusicDataRequest not designed to issue POST requests? Is it something else?
Kind regards!
Hello! I'd like to understand if I can use snippets from songs, such as just the choruses or other parts, like previews for my commercial application, similar to how it's done on TikTok. Can I use them alongside other content? If it's a paid service, how can I find out the cost of such usage?
I was thinking about paying to join the Apple Developer program for access to the Apple Music API, and making an app just for practice in improving my skills. I was looking at the sample response data in the documentation online, and noticed there's some stuff missing that I would want to use. Mainly what songs are in a playlist (it looks like you get that info for a catalog playlist but not a library playlist, which seems backwards but maybe I'm confused about what those mean), and information about particular songs in a user's library like number of plays, date last played, etc. Basically I thought you'd get access to anything you can see in the Apple Music Player on the desktop version. It seems like that's obviously not true but I was surprised, so I thought I'd ask to see if anyone who has used the API can tell me for sure. Probably don't want to pay if you don't get access to all the data I was thinking about.
Hi! I have a 4th gen iPad Air with 17.1 beta 1 version loaded on it. When trying to edit a playlist, every time I remove a song, it always goes back to the top of my playlist, causing me to have to scroll back down. But that’s not the only problem; once I do get back to where I was in my list, and before I can do anything else it will just go back to the top of my list without me doing anything! it doesn’t happen every time but enough times to make it hard for me to continue what I’m trying to do. I have closed the app several times, and even restarted my iPad a few times but still the issues persist! Help? 😅