MusicKit JS

RSS for tag

Add an Apple Music player to your web app using MusicKit JS.

Posts under MusicKit JS tag

25 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

MusicKit Web Playback States
In MusicKit Web the playback states are provided as numbers. For example the playbackStateDidChange event listener will return: {oldState: 2, state: 3, item:...} When the state changes from playing (2) to paused (3). Those are pretty easy to guess, but I'm having a hard time with some of the others: completed, ended, loading, none, paused, playing, seeking, stalled, stopped, waiting. I cannot find a mapping of states to numbers documented anywhere. I got the above states from an enum in a d.ts file that is often incorrect/incomplete. Can someone help out pointing to the docs or provide a mapping? Thanks.
1
0
122
2d
Call Limit of the Apple Music API
We are planning to develop an application using the Apple Music API. We would like to design our system based on the details of the rate limits mentioned below and have a few questions: https://developer.apple.com/documentation/applemusicapi/generating-developer-tokens#Request-Rate-Limiting Regarding the Catalog API (/v1/catalog/*), we understand that server-side caching is enabled, making it less likely to reach the rate limit. Is this understanding correct? (Excluding the search API) For APIs like the Library API (/v1/me/library/*), where responses vary by user, we assume they are more likely to reach the rate limit. Is this correct? We plan to implement optimizations to minimize unnecessary API calls. Given this, would the current Music API be able to handle a significant increase in users? (Assuming a DAU of around 100,000 to 1,000,000) If the API cannot support this scale, would it be allowed under Apple’s policy to cache responses from the Catalog API (/v1/catalog/*) via our proxy server to avoid hitting the rate limit? The third question is the one we most want to confirm.
0
0
127
5d
Issues After Switching to v3
I've been having issues with authorization after switching from v1 to v3, have tried some of the suggestions provided by someone in a reply to a post of mine. Have tried to reach out to Apple Support a few times as well, though I haven't received any support that has helped me to move forward. I have tested my token at https://jwt.io and I'm getting a "Signature Verified", tried multiple browsers in private/incognito mode, now when I try to sign into my Apple Account to test my player I am receiving an error that stats "There is a Problem Connecting. There May be an Issue with Your Network." (which is not the case). I have tried everything I can think of, I'm at a loss and would appreciate any help to get my project moving forward. This is what I am seeing in the browser developer console (using Firefox): Authorization failed: AUTHORIZATION_ERROR: Unauthorized MKError https://js-cdn.music.apple.com/musickit/v3/musickit.js:13 authorize https://js-cdn.music.apple.com/musickit/v3/musickit.js:28 asyncGeneratorStep$w https://js-cdn.music.apple.com/musickit/v3/musickit.js:28 _next https://js-cdn.music.apple.com/musickit/v3/musickit.js:28 media.mydomain.com:398:19 https://media.mydomain.com/:398
5
0
308
4d
Playing music with Musickit.js in Chrome and Firefox
I'm unable to play music using Musickit.js in the Chrome or Firefox browsers. Even using the apple guide here: https://js-cdn.music.apple.com/musickit/v1/index.html - I've added my Music Developer Token and song/album url, but it only works in Safari and not in Chrome or Firefox. I'm unsure if this is a global issue, or if there is something I need to do to enable playback in other browsers, but as it stands it's not working for me. Thanks for any help in advance!
5
0
579
Jan ’25
How to set volume with MusicKit Web?
I've got a web app built with MusicKit that displays a list of songs. I have player controls for play, pause, skip next, skip, previous, toggle shuffle and set repeat mode. All of these work by using music. The play button, when nothing is playing and nothing is in the queue, will enqueue all the tracks and start playing with the below, for example: await music.setQueue({ songs, startPlaying: true }); I've implemented a progress slider based on feedback from the "playbackProgressDidChange" listener. Now, how in the world can I set the volume? This seems like it should be simple, but I am at a complete loss here. The docs say: "The volume of audio playback, which is set directly on the HTMLMediaElement as the HTMLMediaElement.volume property. This value ranges between 0, which would be muting the audio, and 1, which would be the loudest possible." Given that all my controls work off the music instance, I don't understand how I can do that. In this video from WWDC 2022, music web components are touched on briefly. These are also documented very sparsely. The volume docs are here. For the life of me, I can't even get the volume web component to display in the UI. It appears that MusicKit Web is hobbled compared to the native implementation, but surely adjusting volume shouldn't be that hard right? I'd appreciate any insight on how to do this, including how to get web components to work (in a Next JS app). Thanks.
2
0
339
Jan ’25
Music Kit initialisation, Uncaught TypeError: Cannot read properties of undefined (reading 'node')
I'm trying to load Music Kit on the server with solid js. I can confirm that my implementation has been sufficient to return authentication tokens and for MusicKit.isAuthorized to return true. My issue is that if I reload the page, it only succeeds intermittently (perhaps 25% of the time?). My question is - what is wrong with my implementation? Removing the async keyword ensures it loads every time but playing and queuing music no longer works. I'm currently assuming this is an SSR issue but the docs haven't explicitly specified this isn't possible. I have the following boilerplate: export default createHandler( () => ( <StartServer document={({ assets, children, scripts }) => { return ( <html lang="en"> <head> <meta name="apple-music-developer-token" content={authResult.token} /> <meta name="apple-music-app-name" content="app name" /> <meta name="apple-music-app-build" content="1978.4.1" /> {assets} <script src="https://js-cdn.music.apple.com/musickit/v3/musickit.js" async /> </head> <body> <div id="app">{children}</div> {scripts} </body> </html> ) }} /> )) When I first load my app, I'll encounter: musickit.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'node') at musickit.js:13:10194 at musickit.js:13:140 at musickit.js:13:209 The intermittence signals an issue relating to the async keyword. An expansion on this issue can be found here.
0
0
347
Dec ’24
MusicKit - Authorization failed: AUTHORIZATION_ERROR: Unauthorized
Hello, I am having difficulties with configuring MusicKit correctly for my web app that I am building, seeking assistance with the issues I am having. Would greatly appreciate any help! After allowing access to the following, "Access Request media.mydomain.com would like to access Apple Music, media library, and listening activity for myemail'@icloud.com.", I get a popup error that states, "Authorization failed. Please try again.". Following is the information that is given in developer console: [Error] Failed to load resource: the server responded with a status of 403 () (webPlayerLogout, line 0) [Error] Authorization failed: AUTHORIZATION_ERROR: Unauthorized (anonymous function) (media.mydomain.com:398)
6
0
516
4d
Apple music web kit play issues (MusicKit JS)
Hello, I am trying to follow the getting started guide. I have produced a developer token via the music kit embedding approach and can confirm I'm successfully authorized. When I try to do play music, I'm unable to hear anything. Thought it could be some auto-play problems with the browser, but it doesn't appear to be related, as I can trigger play from a button with no further success. const music = MusicKit.getInstance() try { await music.authorize() // successful const result = await music.api.music(`/v1/catalog/gb/search`, { term: 'Sound Travels', types: 'albums', }) await music.play() } catch (error) { console.error('play error', error) // ! No error triggered } I have searched the forum, have found similar queries but apparently none using V3 of the API. Other potentially helpful information: OS: macos 15.1 (24B83) API version: V3 On localhost Browser: Arc (chromium based), also tried on Safari, The only difference between the two browsers is that safari appears to exit the breakpoint, whereas Arc will continue (without throwing any errors) authorizationStatus: 3 Side note, any reason this is still in beta so many years later?
1
0
445
Dec ’24
Evidently I'm not generating API tokens right.
I'm trying (in Swift) to use CryptoKit to generate the required JWT for the Apple Music Web API, as documented (sort of) here. But I'm getting 401s no matter what I try. I found some examples of generating JWTs online, but something isn't working here. I've set up my identifiers and gotten an API secret through my account in the dev portal. It's associated with an identifier requesting Music API access (I requested all three available Music-related capabilities). For the secret, I'm using the long key string from the .p8 file I generated and downloaded from the dev portal. Here's what I've tried: struct APIToken { struct Header: Encodable { let alg = "HS256" let kid: String } struct Payload: Encodable { let iss: String let iat: String let exp: String } static func tokenize(keyID: String, issuerID: String, secret: String) -> String { let privateKey = SymmetricKey(data: Data(secret.utf8)) let headerJSONData = try! JSONEncoder().encode(Header(kid: keyID)) let headerBase64String = headerJSONData.base64EncodedString() let currUnixTime = Int(Date().timeIntervalSince1970) let expUnixTime = currUnixTime + 5 * 2628288 // five months of seconds let payloadJSONData = try! JSONEncoder().encode(Payload(iss: issuerID, iat: "\(currUnixTime)", exp: "\(expUnixTime)")) let payloadBase64String = payloadJSONData.base64EncodedString() let toSign = Data((headerBase64String + "." + payloadBase64String).utf8) let signature = HMAC<SHA256>.authenticationCode(for: toSign, using: privateKey) let signatureBase64String = Data(signature).base64EncodedString() let token = [headerBase64String, payloadBase64String, signatureBase64String].joined(separator: ".") print(token) return token } } I also tried making sure the base64 strings are URL-safe with this extension: extension Data { func URLSafeBase64EncodedString() -> String { return base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") } } but that made no difference. All the documentation says is A decoded developer token has the following format. { "alg": "ES256", "kid": "ABC123DEFG" } { "iss": "DEF123GHIJ", "iat": 1437179036, "exp": 1493298100 } After you create the token, sign it with your MusicKit private key using the ES256 algorithm. Am I not doing that? Any insight appreciated.
0
0
289
Nov ’24
Music Kit HTML Embeds move an 490 px and below
Apple provides HTML Embeds for Music Kit JS, as mentioned here. There is a tool here that you can use to create embeds. Scroll to Preview Player. Now, if you set your browser width to less than 490 (right when the thumbnail gets smaller), the player will move vertically if you drag up. Not by much, it's hard to see without a contrasting background.. It's more noticeable in dark mode, as a white background shows clearly, like this: I'm misusing "drag" here: a simple, vertical scroll will cause this. Since this happens on Apple's own site, I'm fairly certain that this is not a "me problem," but who knows! Anyhow, I'm not sure if anyone has come across this. These embeds are pretty handy, and I'm loathe to roll my own player just to fix this. Any constructive advice would be appreciated.
2
0
401
Oct ’24
Integrating Apple Music Subscriptions into a React Native App
Hi everyone, I'm currently developing an iOS app using React Native and recently got accepted into the Apple Music Global Affiliate Program. To fully utilize this opportunity, I need to implement the following functionalities: Authorize Apple Music usage Play Apple Music within my app Identify if a user has an Apple Music subscription Initiate and complete Apple Music subscription within my app I've successfully implemented the first three functionalities using the react-native-apple-music module. Now, I need your help to understand how I can directly trigger the Apple Music subscription process from within my app. Thank you for your help!
0
1
748
Jun ’24
Music Kit for web app
Hello there, I am faced with the following situation: We are building a web app that manages playlists for different platforms, including Apple music We have the concept of teams in there, where a user can be part of multiple teams, and teams are managed by team admin A team admin could manage multiple teams The problem here is, that a team admin wouldn't be able to sign in to the Apple music account for multiple teams because if using the same computer we try to let the user sign in once and store the Music User Token, we can't do another login unless we unauthorized the previous one. Is there anything we can do about this? Thanks
1
0
818
Jun ’24
MusicKit WebAPI - Can only get storefronts. All other endpoints return 500
Hello, Problem I am having the exact same issue as described here : https://forums.developer.apple.com/forums/thread/693310 From my understanding of the answers on this topic, it appears to be a problem on the Server Side. Is it still the case or perhaps I am missing something ? Here are the curl commands and their outputs : Storefront call ➜ ~ curl -v -H 'Authorization: Bearer [VALID TOKEN]' "https://api.music.apple.com/v1/storefronts/us" * Trying [2a02:26f0:2b00:3ab::2a1]:443... * Connected to api.music.apple.com (2a02:26f0:2b00:3ab::2a1) port 443 (#0) * ALPN: offers h2 * ALPN: offers http/1.1 * CAfile: /etc/ssl/cert.pem * CApath: none * [CONN-0-0][CF-SSL] (304) (OUT), TLS handshake, Client hello (1): * [CONN-0-0][CF-SSL] (304) (IN), TLS handshake, Server hello (2): * [CONN-0-0][CF-SSL] (304) (IN), TLS handshake, Unknown (8): * [CONN-0-0][CF-SSL] (304) (IN), TLS handshake, Certificate (11): * [CONN-0-0][CF-SSL] (304) (IN), TLS handshake, CERT verify (15): * [CONN-0-0][CF-SSL] (304) (IN), TLS handshake, Finished (20): * [CONN-0-0][CF-SSL] (304) (OUT), TLS handshake, Finished (20): * SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256 * ALPN: server accepted h2 * Server certificate: * subject: businessCategory=Private Organization; jurisdictionCountryName=US; jurisdictionStateOrProvinceName=California; serialNumber=C0806592; C=US; ST=California; L=Cupertino; O=Apple Inc.; CN=itunes.apple.com * start date: Jan 23 20:23:43 2024 GMT * expire date: Jul 21 20:33:43 2024 GMT * subjectAltName: host "api.music.apple.com" matched cert's "api.music.apple.com" * issuer: C=US; O=Apple Inc.; CN=Apple Public EV Server RSA CA 2 - G1 * SSL certificate verify ok. * Using HTTP2, server supports multiplexing * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0 * h2h3 [:method: GET] * h2h3 [:path: /v1/storefronts/us] * h2h3 [:scheme: https] * h2h3 [:authority: api.music.apple.com] * h2h3 [user-agent: curl/7.87.0] * h2h3 [accept: */*] * h2h3 [authorization: Bearer [VALID TOKEN]] * Using Stream ID: 1 (easy handle 0x12680a800) > GET /v1/storefronts/us HTTP/2 > Host: api.music.apple.com > user-agent: curl/7.87.0 > accept: */* > authorization: Bearer [VALID TOKEN] > < HTTP/2 200 < server: daiquiri/5 < content-type: application/json;charset=utf-8 < x-apple-jingle-correlation-key: QZSH3IR75IPQYS7LSN5C5EUJRI < x-apple-request-uuid: 86647da2-3fea-1f0c-4beb-937a2e92898a < b3: 86647da23fea1f0c4beb937a2e92898a-1d7eb7b8ad18bc4d < x-b3-traceid: 86647da23fea1f0c4beb937a2e92898a < x-b3-spanid: 1d7eb7b8ad18bc4d < apple-seq: 0.0 < apple-tk: false < apple-originating-system: MZStorePlatform < x-apple-application-site: MR22 < x-apple-application-instance: 3588504 < x-responding-instance: MZStorePlatform:3588504::: < apple-timing-app: 4 ms < access-control-allow-origin: * < strict-transport-security: max-age=31536000; includeSubDomains < x-daiquiri-instance: daiquiri:11896006:mr84p00it-qujn09092102:7987:24RELEASE93:daiquiri-amp-store-l7shared-int-001-mr < x-daiquiri-instance: daiquiri:12282002:mr47p00it-qujn07081302:7987:24RELEASE93:daiquiri-amp-store-l7shared-ext-001-mr < cache-control: public, no-transform, max-age=2625 < date: Tue, 23 Apr 2024 14:08:00 GMT < content-length: 276 < x-cache: TCP_REFRESH_MISS from a2-17-114-29.deploy.akamaitechnologies.com (AkamaiGHost/11.4.5-55391218) (S) < x-cache-remote: TCP_HIT from a2-17-114-18.deploy.akamaitechnologies.com (AkamaiGHost/11.4.5-55391218) (-) < vary: Accept-Encoding < vary: Accept-Encoding < * Connection #0 to host api.music.apple.com left intact {"data":[{"id":"us","type":"storefronts","href":"/v1/storefronts/us","attributes":{"supportedLanguageTags":["en-US","es-MX","ar","ru","zh-Hans-CN","fr-FR","ko","pt-BR","vi","zh-Hant-TW"],"explicitContentPolicy":"allowed","name":"United States","defaultLanguageTag":"en-US"}}]}% Album call ➜ ~ curl -v -H 'Authorization: Bearer [VALID TOKEN]' "https://api.music.apple.com/v1/catalog/us/albums/310730204" * Trying [2a02:26f0:2b00:3ab::2a1]:443... * Connected to api.music.apple.com (2a02:26f0:2b00:3ab::2a1) port 443 (#0) * ALPN: offers h2 * ALPN: offers http/1.1 * CAfile: /etc/ssl/cert.pem * CApath: none * [CONN-0-0][CF-SSL] (304) (OUT), TLS handshake, Client hello (1): * [CONN-0-0][CF-SSL] (304) (IN), TLS handshake, Server hello (2): * [CONN-0-0][CF-SSL] (304) (IN), TLS handshake, Unknown (8): * [CONN-0-0][CF-SSL] (304) (IN), TLS handshake, Certificate (11): * [CONN-0-0][CF-SSL] (304) (IN), TLS handshake, CERT verify (15): * [CONN-0-0][CF-SSL] (304) (IN), TLS handshake, Finished (20): * [CONN-0-0][CF-SSL] (304) (OUT), TLS handshake, Finished (20): * SSL connection using TLSv1.3 / AEAD-CHACHA20-POLY1305-SHA256 * ALPN: server accepted h2 * Server certificate: * subject: businessCategory=Private Organization; jurisdictionCountryName=US; jurisdictionStateOrProvinceName=California; serialNumber=C0806592; C=US; ST=California; L=Cupertino; O=Apple Inc.; CN=itunes.apple.com * start date: Jan 23 20:23:43 2024 GMT * expire date: Jul 21 20:33:43 2024 GMT * subjectAltName: host "api.music.apple.com" matched cert's "api.music.apple.com" * issuer: C=US; O=Apple Inc.; CN=Apple Public EV Server RSA CA 2 - G1 * SSL certificate verify ok. * Using HTTP2, server supports multiplexing * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0 * h2h3 [:method: GET] * h2h3 [:path: /v1/catalog/us/albums/310730204] * h2h3 [:scheme: https] * h2h3 [:authority: api.music.apple.com] * h2h3 [user-agent: curl/7.87.0] * h2h3 [accept: */*] * h2h3 [authorization: Bearer [VALID TOKEN]] * Using Stream ID: 1 (easy handle 0x148010a00) > GET /v1/catalog/us/albums/310730204 HTTP/2 > Host: api.music.apple.com > user-agent: curl/7.87.0 > accept: */* > authorization: Bearer [VALID TOKEN] > < HTTP/2 500 < server: daiquiri/5 < content-type: application/json; charset=utf-8 < content-length: 42 < access-control-allow-origin: * < x-apple-jingle-correlation-key: EABGYDVEO5AFSK47FMXBMUMODY < x-apple-application-site: st < strict-transport-security: max-age=31536000; includeSubDomains < x-daiquiri-instance: daiquiri:42282002:st53p00it-qujn13050102:7987:24RELEASE93:daiquiri-amp-store-l7shared-ext-001-st < date: Tue, 23 Apr 2024 14:08:03 GMT < x-cache: TCP_MISS from a2-17-114-29.deploy.akamaitechnologies.com (AkamaiGHost/11.4.5-55391218) (-) < * Connection #0 to host api.music.apple.com left intact {"message":"An unexpected error occurred"}% Am I missing something ? Is it a server side issue ? If so, when will it be fixed ? Otherwise, what is wrong with my approach ?
0
0
748
Apr ’24
Flutter with Music Kit
Has anyone found a way to retrieve user token if I want to make an app on Flutter that uses that to make Apple Music API calls to just retrieve the user data and display it on the application? Something like when a user opens their app, there is a button that says connect with apple. It takes the user to give permissions for apple music and that retrieves their user token. I know there is Music Kit on Swift but i wonder if there is something like that on flutter
0
0
985
Apr ’24
CORS
Access to fetch at 'https://play.itunes.apple.com/WebObjects/MZPlay.woa/wa/webPlayback' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
1
0
777
Mar ’24