### Get MusicKit Instance Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit--page&viewMode=story Access the configured MusicKit Instance singleton. `configure()` must have been called first, otherwise this will return `undefined`. ```javascript const music = MusicKit.getInstance(); ``` -------------------------------- ### skipToNextItem Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page Starts playback of the next item in the playback queue. ```APIDOC ## skipToNextItem ### Description Starts playback of the next item in the playback `queue`. ### Method `skipToNextItem` ### Response #### Success Response (Promise) Returns a Promise that resolves when the next item starts playing. ``` -------------------------------- ### skipToNextItem Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page&viewMode=story Starts playback of the next item in the playback queue. This method returns a Promise that resolves with void. ```APIDOC ## skipToNextItem ### Description Starts playback of the next item in the playback `queue`. ### Method `skipToNextItem(): Promise` ``` -------------------------------- ### Artwork Object Example Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=using-album-art-and-images--page&viewMode=story An example of an Artwork object structure as returned by the Apple Music API. ```json "artwork": { "width": 3000, "height": 3000, "url": "https://is1-ssl.mzstatic.com/image/thumb/Music125/v4/33/fd/32/33fd32b1-0e43-9b4a-8ed6-19643f23544e/21UMGIM26092.rgb.jpg/{w}x{h}bb.jpg", "bgColor": "675f9a", "textColor1": "f3f6fb", "textColor2": "fbeaf0", "textColor3": "d7d8e8", "textColor4": "decedf" } ``` -------------------------------- ### Async Loop to Fetch All Playlist Tracks and Initiate Playback Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=paginated-requests--page An example of an asynchronous loop that continuously fetches pages of playlist tracks using the 'next' property until all data is retrieved. It then initiates playback of the collected tracks. ```javascript const pageSize = 25; const playlistId = 'pl.9b8a976ba78741d9925e6e9a050703de'; const urlPath = `/v1/catalog/{{storefrontId}}/playlists/${playlistId}/tracks`; const tracks = []; const music = MusicKit.getInstance(); let hasNextPage = true; while (hasNextPage) { const queryParameters = { // Page size is always consistent limit: pageSize, // The length of the list of objects // is also the index of the next object, // assuming we started with the 0th object offset: tracks.length, }; // Make a request for the next page const { data: { data: dataForPage = [], next } } = await music.api.music(urlPath, queryParameters); // Push the results to the cumulative array of objects tracks.push(...dataForPage); // Cast the `next` property to a boolean, where `undefined` // becomes `false`, but any URL value would be `true` // // When this is `false`, then the loop stops hasNextPage = !!next; } // Outside of the loop, `tracks` now contains results from all pages // Initiate playback of the `tracks` await music.setQueue({ items: tracks }); await music.play(); ``` -------------------------------- ### skipToPreviousItem Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page Starts playback of the previous item in the playback queue. ```APIDOC ## skipToPreviousItem ### Description Starts playback of the previous item in the playback `queue`. ### Method `skipToPreviousItem` ### Response #### Success Response (Promise) Returns a Promise that resolves when the previous item starts playing. ``` -------------------------------- ### skipToPreviousItem Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page&viewMode=story Starts playback of the previous item in the playback queue. This method returns a Promise that resolves with void. ```APIDOC ## skipToPreviousItem ### Description Starts playback of the previous item in the playback `queue`. ### Method `skipToPreviousItem(): Promise` ``` -------------------------------- ### MusicKit Instance Properties Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page&viewMode=story Properties of the MusicKit instance that allow you to get information about the current playback state, control playback settings, and access related objects. ```APIDOC ## MusicKit Instance Properties ### `api` **Type:** `MusicKitAPI` See Accessing Content via the Apple Music API for more information. ### `bitrate` **Type:** `MusicKit.PlaybackBitrate` The bit rate for the media player. The bit rate is set automatically based on the client, but can be overridden by the app to a value from the enum `MusicKit.PlaybackBitrate`. Setting this property will affect the item played _next_ , not the currently playing item. This property does not necessarily represent the actual bit rate of the item being played, only the target bit rate when the player selects the stream to play. **Example** ```javascript const music = MusicKit.getInstance(); // Instruct MusicKit to prefer the high-bit rate assets, when available music.bitrate = MusicKit.PlaybackBitrate.HIGH; ``` ### `currentPlaybackDuration` **Type:** `Number` _read-only_ The duration of the `nowPlayingItem`, in seconds. ### `currentPlaybackProgress` **Type:** `Number` _read-only_ Progress percentage between `0` and `1` indicating the current play head position for the `nowPlayingItem`. Useful for showing a playback progress bar UI, for instance. ### `currentPlaybackTime` **Type:** `Number` _read-only_ The current position of the play head for the `nowPlayingItem`, in seconds. ### `currentPlaybackTimeRemaining` **Type:** `Number` _read-only_ The current remaining playback time for the `nowPlayingItem`, in seconds. ### `isAuthorized` **Type:** `Boolean` _read-only_ This is set to `true` after the user successfully signs in and authorizes the application via the `authorize()` method, or upon configuring the MusicKit instance if the user had previously authorized your application. ### `isPlaying` **Type:** `Boolean` _read-only_ Indicates whether the player is in the playing state. ### `nowPlayingItem` **Type:** `MediaItem` or `undefined` _read-only_ This is the `MediaItem` that is currently playing from the `Queue`. This property will change when playback of a `Queue` starts, but will not unset on pause. It will change to the next item in the `Queue` once that item starts playing. ### `nowPlayingItemIndex` **Type:** `Number` _read-only_ The index of the `nowPlayingItem` in the current playback `Queue`. ### `playbackRate` **Type:** `Number` The speed of playback, which is set directly on the `HTMLMediaElement` as the `HTMLMediaElement.playbackRate` property. The default rate is `1.0`, but this can be set to a value higher or lower to control the speed of playback. Different browsers will have different upper and lower bounds for this value. ### `playbackState` **Type:** `MusicKit.PlaybackStates` _read-only_ The current playback state of the media player. See the Enum `MusicKit.PlaybackStates` for more information and the possible values. ### `previewOnly` **Type:** `Boolean` When a user with a valid Apple Music subscription authorizes your app, MusicKit will allow full playback of content from the Apple Music catalog. If the app does not have user authorization, then playback is restricted to non-DRM preview assets, which are snippets of the full media. You can set this property to `true` to restrict MusicKit to playing only the preview assets, even when full playback is available. Setting this to `false` will not force full playback, but will instead return to the default behavior of determining what asset to play based on the user’s authorization and Apple Music Subscription status. ### `queue` **Type:** `Queue` _read-only_ The current playback queue of the music player. ### `queueIsEmpty` **Type:** `Boolean` Indicates whether the current playback `queue` is empty. ### `repeatMode` **Type:** `MusicKit.PlayerRepeatMode` Set this to an Enum value from `MusicKit.PlayerRepeatMode` to control the repeat behavior during playback. **Example** ```javascript const music = MusicKit.getInstance(); // Setting to mode `all` will repeat the current queue after // we play through it entirely music.repeatMode = MusicKit.PlayerRepeatMode.all; ``` ``` -------------------------------- ### play Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page Starts or resumes playback of the current media item. Note that this action may fail if the user has not yet interacted with the player, as browsers often restrict audio playback initiation without user consent. ```APIDOC ## play ### Description Initiates playback of the `nowPlayingItem`. **Note:** This could result in an error if the user has not interacted with the player yet, as most browsers prevent audio playback without user interaction. ### Method Signature `play(): void` ``` -------------------------------- ### Listen for Now Playing Item Will Change Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-events--page&viewMode=story Use this event to get notified just before the currently playing media item is about to change. It provides access to the upcoming item's attributes. ```javascript const music = MusicKit.getInstance(); music.addEventListener('nowPlayingItemWillDidChange', ({ item }) => { const { name, artistName } = item.attributes; console.log(`Will change to playing ${name} ${artistName}`); }); ``` -------------------------------- ### Configure MusicKit Instance Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Freference-javascript-musickit--page Use `MusicKit.configure` to set up the MusicKit instance with your application's configuration. This method requires a `developerToken` and application details. It returns a Promise that resolves with the configured MusicKit instance. ```javascript const music = await MusicKit.configure({ developerToken: "YOUR_DEVELOPER_TOKEN", app: { name: "My Music App", build: "1.0.0", icon: "URL_TO_APP_ICON" } }); ``` -------------------------------- ### Get Next Page URL using 'next' Property Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=paginated-requests--page Shows how to use the 'next' property in an API response to get the URL for the subsequent page of results. The 'next' property is present when more data is available. ```javascript const playlistId = 'pl.9b8a976ba78741d9925e6e9a050703de'; const urlPath = `/v1/catalog/{{storefrontId}}/playlists/${playlistId}/tracks`; const { data: { next } } = await music.api.music(urlPath, { limit: 10 }); console.log(next); // '/v1/catalog/us/playlists/pl.9b8a976ba78741d9925e6e9a050703de/tracks?offset=10' ``` -------------------------------- ### MusicKit.configure Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fstory%2Freference-javascript-musickit--page Configures MusicKit on the Web and returns a Promise that resolves with the configured MusicKit Instance. This is the primary method for initializing MusicKit. ```APIDOC ## MusicKit.configure ### Description Configures MusicKit on the Web. This method must be called before accessing the MusicKit instance. ### Method `configure( config: MusicKitConfiguration ): Promise ### Parameters #### `config` (MusicKitConfiguration) - Required ##### `MusicKitConfiguration` Object - `developerToken` (String) - Required - Your developer token for authentication. - `app` (Object) - Required - `name` (String) - Required - The name of your application. - `build` (String) - Optional - The current build number or version of your app. - `icon` (String) - Optional - A URL to your application's icon. - `bitrate` (MusicKit.PlaybackBitrate) - Optional - The desired bitrate for playback. - `storefrontId` (String) - Optional - The default storefront ID for requests. ### Return Value A Promise that resolves with the configured MusicKit Instance. ``` -------------------------------- ### Configure MusicKit v1 vs v3 Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=tech-notes-migrating-to-v3--page Illustrates the change in the `configure` method signature from an synchronous call in v1 to an asynchronous Promise-based call in v3. You should await the promise before calling `MusicKit.getInstance()` in v3. ```javascript const music = MusicKit.configure({}) ``` ```javascript const music = await MusicKit.configure({}) ``` -------------------------------- ### MusicKit.configure Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit--page&viewMode=story Configures MusicKit on the web and returns a Promise that resolves with the configured MusicKit Instance. It requires a developer token and application details. ```APIDOC ## MusicKit.configure ### Description Configures MusicKit on the web. This method must be called before accessing the MusicKit instance. ### Method `configure(config: MusicKitConfiguration): Promise` ### Parameters #### `config` (MusicKitConfiguration) - Required * `developerToken` (String) - Required * `app` (Object) - Required * `app.name` (String) - Required - The name of your application during the authorization flow. * `app.build` (String) - Optional - Current build number or version of your app. * `app.icon` (String) - Optional - A URL to the image used to represent your application during the authorization flow. * `bitrate` (MusicKit.PlaybackBitrate) - Optional - Can be used to target a bit rate for playback. * `storefrontId` (String) - Optional - The value used for the `{{storefrontId}}` token in the `path` argument of the Passthrough API method. ### Return Value Returns a Promise that resolves with the configured MusicKit Instance. ``` -------------------------------- ### MusicKit.getInstance Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit--page&viewMode=story Accesses the singleton MusicKit Instance. This method should only be called after `configure()` has been successfully invoked. ```APIDOC ## MusicKit.getInstance ### Description Accesses the configured MusicKit Instance singleton. Ensure `configure()` has been called prior to using this method. ### Method `getInstance(): MusicKitInstance` ### Return Value Returns the singleton MusicKit Instance. Returns `undefined` if `configure()` has not been called. ### Example ```javascript const music = MusicKit.getInstance(); ``` ``` -------------------------------- ### Listen for the `musickitloaded` Event Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=get-started--page&viewMode=story MusicKit on the Web loads asynchronously. Use this event listener to ensure the `MusicKit` global is available before interacting with it. ```javascript document.addEventListener('musickitloaded', async function () { // MusicKit global is now defined. }); ``` -------------------------------- ### changeToMediaItem Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page&viewMode=story Starts playing a specific MediaItem from the queue immediately, identified by either a MediaItem instance or its ID. Similar to `changeToMediaAtIndex`, this can trigger playback and may require user interaction. ```APIDOC ## changeToMediaItem ### Description Begins playing a specific `MediaItem` in the `queue` immediately. **Note:** This method will trigger playback, even if the player is currently paused. This could result in an error if the user has not interacted with the player yet, as most browsers prevent audio playback without user interaction. See also `setQueue` ### Method Signature `changeToMediaItem(descriptor: MediaItem | String): Promise` ### Parameters * `descriptor` (MediaItem | String) - Required. The descriptor can be a `MediaItem` instance or the `id` of a specific item in the `queue`. ``` -------------------------------- ### changeToMediaItem Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page Starts playing a specific media item from the queue immediately, identified by either a MediaItem object or its ID. Similar to `changeToMediaAtIndex`, this can trigger playback and may require user interaction. ```APIDOC ## changeToMediaItem ### Description Begins playing a specific `MediaItem` in the `queue` immediately. **Note:** This method will trigger playback, even if the player is currently paused. This could result in an error if the user has not interacted with the player yet, as most browsers prevent audio playback without user interaction. See also `setQueue` ### Method Signature `changeToMediaItem(descriptor: MediaItem | String): Promise` ### Parameters * `descriptor` (MediaItem | String) - The descriptor can be a `MediaItem` instance or the `id` of a specific item in the `queue`. ``` -------------------------------- ### Fetch All Recommendations Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Fetches all recommendations for the user. ```APIDOC ## GET /v1/me/recommendations ### Description Fetch all recommendations. ### Method GET ### Endpoint /v1/me/recommendations ### Parameters #### Query Parameters - **l** (string) - Optional - The language code for the response. ### Request Example ```javascript const queryParameters = { l: 'en-us' }; await music.api.music(`/v1/me/recommendations`, queryParameters); ``` ``` -------------------------------- ### Fetch First and Second Pages of Playlist Tracks Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=paginated-requests--page Demonstrates fetching the first page of results with a specified limit and then fetching the second page by using the offset parameter. ```javascript const playlistId = 'pl.9b8a976ba78741d9925e6e9a050703de'; const urlPath = `/v1/catalog/{{storefrontId}}/playlists/${playlistId}/tracks`; // Fetch first page of results, limiting the size of the page const { data: { data: pageOneData = [] } } = await music.api.music(urlPath, { limit: 10 }); // Fetch the second page, which is starting with the object in the index // position that is after the last item in the previous page (0-based) const { data: { data: pageTwoData = [] } } = await music.api.music(urlPath, { limit: 10, offset: 10 }); ``` -------------------------------- ### changeToMediaAtIndex Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page&viewMode=story Starts playing the MediaItem at the specified index in the current queue immediately. This method will trigger playback even if the player is paused and may result in an error if user interaction is required. ```APIDOC ## changeToMediaAtIndex ### Description Begins playing the MediaItem at the specified index in the `queue` immediately. **Note:** This method will trigger playback, even if the player is currently paused. This could result in an error if the user has not interacted with the player yet, as most browsers prevent audio playback without user interaction. ### Method Signature `changeToMediaAtIndex(index: Number): Promise` ### Parameters * `index` (Number) - Required. The index position of the `MediaItem` in the `queue` to begin playing. ``` -------------------------------- ### changeToMediaAtIndex Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page Starts playing the media item at a specific index in the current queue. This method will initiate playback even if the player is paused, but may result in an error if user interaction is required for audio playback. ```APIDOC ## changeToMediaAtIndex ### Description Begins playing the MediaItem at the specified index in the `queue` immediately. **Note:** This method will trigger playback, even if the player is currently paused. This could result in an error if the user has not interacted with the player yet, as most browsers prevent audio playback without user interaction. ### Method Signature `changeToMediaAtIndex(index: Number): Promise` ### Parameters * `index` (Number) - The index position of the `MediaItem` in the `queue` to begin playing. ``` -------------------------------- ### Fetch Search Hints - MusicKit JS Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Fetch search term suggestions based on a query. Requires a storefront ID and locale. ```javascript const queryParameters = { term: 'Taylor Swift', l: 'en-us' }; await music.api.music('/v1/catalog/{{storefrontId}}/search/hints', queryParameters); ``` -------------------------------- ### Async Configuration in MusicKit v3 Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=tech-notes-migrating-to-v3--page&viewMode=story In MusicKit v3, MusicKit.configure() is now asynchronous and returns a Promise. You should await this promise before using MusicKit.getInstance(). ```javascript const music = await MusicKit.configure({}) ``` -------------------------------- ### MusicKit JS Controls - Sign In Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fstory%2Fhtml-embeds--html-embeds Provides a button to initiate the sign-in process for MusicKit JS. ```html ``` -------------------------------- ### MusicKit JS Sign In Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Fhtml-embeds--html-embeds Initiates the sign-in process for MusicKit JS. Ensure MusicKit is properly configured before calling. ```javascript MusicKit.getInstance().authorize(); ``` -------------------------------- ### Cloud Library API Request Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=accessing-music-content--page&viewMode=story Access a user's Cloud Library by making requests to Apple Music Web Service API methods starting with `v1/me/library`. User authorization is required before making these calls. ```javascript const music = MusicKit.getInstance(); // You should check authorization before accessing user's iCloud Music Library: await music.authorize(); const result = await music.api.music('v1/me/library/albums'); ``` -------------------------------- ### Async Configuration in MusicKit JS v3 Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fstory%2Ftech-notes-migrating-to-v3--page When configuring MusicKit JS in v3, you must now await the `configure` method as it returns a Promise. This ensures that the MusicKit instance is ready before you attempt to use it. ```javascript const music = await MusicKit.configure({}); ``` -------------------------------- ### Fetch All Recommendations Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Retrieve all recommendations for the user. Localization can be specified using the 'l' query parameter. ```javascript const queryParameters = { l: 'en-us' }; await music.api.music(`/v1/me/recommendations`, queryParameters); ``` -------------------------------- ### MusicKit JS Set Queue (Live Station) Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Fhtml-embeds--html-embeds Sets the playback queue to a live station using MusicKit JS. Requires a valid station identifier. ```javascript MusicKit.getInstance().setQueue({"contentType":"station","globalID":"1234567890","isLive":true}); ``` -------------------------------- ### Set Queue from Playlist URL Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-queue--page Use `setQueue` with a URL to create a new queue from the content referenced by the URL. This abstracts the need to know the content type beforehand. ```javascript const music = MusicKit.getInstance(); const playlistURL = 'https://music.apple.com/us/playlist/pl.d133de76fb4f4ccf98846231899874c0'; await music.setQueue({ url: playlistURL }); ``` -------------------------------- ### Set Queue from Playlist ID and Play Next Song Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-queue--page Use `setQueue` with a playlist ID to create a new queue and `playNext` with a song ID to add a song to the current queue. ```javascript const music = MusicKit.getInstance(); // Create a new queue from a playlist await music.setQueue({ playlist: 'pl.d133de76fb4f4ccf98846231899874c0', startPlaying: true }); // Update the current queue to add a song after the currently playing one await music.playNext({ song: '1561837008' }); ``` -------------------------------- ### Make a Catalog Request using api.music() Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Use the `api.music()` method to fetch data from the Apple Music API catalog. The `{{storefrontId}}` token is automatically replaced with the user's current storefront. This method handles JWT and MUT headers. ```javascript const music = MusicKit.getInstance(); // {{storefrontId}} is replaced with the current user’s storefront automatically const result = await music.api.music('/v1/catalog/{{storefrontId}}/albums/1025210938'); ``` -------------------------------- ### Fetch Next Page Directly Using 'next' URL Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=paginated-requests--page Illustrates using the 'next' property's value directly to fetch the next page of data. Note that the 'limit' parameter might need to be re-specified if a non-default page size is desired. ```javascript const playlistId = 'pl.9b8a976ba78741d9925e6e9a050703de'; const pageOneUrl = `/v1/catalog/{{storefrontId}}/playlists/${playlistId}/tracks`; const { data: { data: pageOneData, next: pageTwoUrl } } = await music.api.music(pageOneUrl, { limit: 10 }); const { data: { data: pageTwoData } } = await music.api.music(pageTwoUrl, { limit: 10 }); ``` -------------------------------- ### Listen for MusicKit Configuration Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-events--page&viewMode=story Add an event listener to the MusicKit instance to be notified when the instance has been configured. ```javascript const music = MusicKit.getInstance(); music.addEventListener('configured', () => { console.log('MusicKit is not configured'); }); ``` -------------------------------- ### Fetch Storefront by ID Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?path=%2Fstory%2Freference-javascript-api--page Fetches a single storefront using its unique identifier and an optional locale. ```APIDOC ## Fetch Storefront by ID ### Description Fetches a storefront using its identifier. ### Method GET ### Endpoint /v1/storefronts/{storefrontId} ### Parameters #### Path Parameters - **storefrontId** (string) - Required - The identifier of the storefront. #### Query Parameters - **l** (string) - Optional - The locale for the response (e.g., 'en-us'). ### Request Example ```javascript const storefrontId = '123456789'; const queryParameters = { l: 'en-us' }; await music.api.music(`/v1/storefronts/${storefrontId}`, queryParameters); ``` ``` -------------------------------- ### authorize Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page&viewMode=story Initiates the user authorization process, returning a Promise that resolves with a string representing the user or undefined if authorization fails or is canceled. ```APIDOC ## authorize ### Description See User Authorization for more information. ### Method Signature `authorize(): Promise` ### Return Value Returns a Promise that resolves with a string representing the user. If authorization fails or is canceled by the user, the resolved value is `undefined`. ``` -------------------------------- ### Play Music Previews and Full Tracks Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=user-authorization--page Demonstrates playing music previews without authorization. For full-length playback or accessing the user's iCloud Music Library, authorization must be obtained first. This snippet shows checking authorization before playing full tracks and accessing library data. ```javascript const music = MusicKit.getInstance(); // Music previews can be played without authorization: await music.play(); // To play the full length of a song, check authorization before calling play(): await music.authorize(); await music.play(); // You should check authorization before accessing user's iCloud Music Library: await music.authorize(); const { data: result } = await music.api.music('v1/me/library/albums'); // User's iCloud Music Library Albums console.log(result.data); ``` -------------------------------- ### authorize Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page Initiates the user authorization process, returning a Promise that resolves with a string representing the authorized user or undefined if authorization fails or is canceled. ```APIDOC ## authorize ### Description Initiates the user authorization process. See User Authorization for more information. ### Method Signature `authorize(): Promise` ### Return Value Returns a Promise that resolves with a string representing the user. If authorization fails or is canceled by the user, the resolved value is `undefined`. ``` -------------------------------- ### Fetch Multiple Storefronts Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Retrieve multiple storefronts by providing an array of their IDs. Specify the locale for the response. ```javascript const queryParameters = { ids: ['1233456789', '987654321'], l: 'en-us' }; await music.api.music(`/v1/storefronts`, queryParameters); ``` -------------------------------- ### Configure MusicKit on the Web Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=get-started--page&viewMode=story Configure MusicKit on the Web using your developer token and app details. This code should be placed within the `musickitloaded` event listener. ```javascript document.addEventListener('musickitloaded', async function () { // Call configure() to configure an instance of MusicKit on the Web. try { await MusicKit.configure({ developerToken: 'DEVELOPER-TOKEN', app: { name: 'My Cool Web App', build: '1978.4.1', }, }); } catch (err) { // Handle configuration error } // MusicKit instance is available const music = MusicKit.getInstance(); }); ``` -------------------------------- ### queue Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Freference-javascript-musickit-instance--page The current playback queue of the music player. ```APIDOC ## `queue` ### Description The current playback queue of the music player. ### Type `Queue` (read-only) ``` -------------------------------- ### MusicKit JS Set Queue (Music Video) Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Fhtml-embeds--html-embeds Sets the playback queue to a music video using MusicKit JS. Requires a valid music video identifier. ```javascript MusicKit.getInstance().setQueue({"contentType":"musicVideo","globalID":"1234567890"}); ``` -------------------------------- ### MusicKit JS Controls - Set Queue Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fstory%2Fhtml-embeds--html-embeds Allows setting the playback queue with various content types like albums, playlists, and songs. ```html ``` -------------------------------- ### Play Media Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page Initiates playback of the `nowPlayingItem`. Note that this may result in an error if the user has not interacted with the player, as browsers often prevent audio playback without user interaction. ```javascript music.play(); ``` -------------------------------- ### Fetch Activities - MusicKit JS Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Fetch one or more activities using their identifiers. Requires a storefront ID and locale. ```javascript const queryParameters = { ids: ['1233456789', '987654321'], l: 'en-us' }; await music.api.music(`/v1/catalog/{{storefrontId}}/activities`, queryParameters); ``` -------------------------------- ### Charts Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?path=%2Fstory%2Freference-javascript-api--page Fetch chart information for a given storefront. ```APIDOC ## Charts ### Description Fetch chart information for a given storefront. ### Method GET ### Endpoint `/v1/catalog/{storefrontId}/charts` ### Parameters #### Query Parameters - **types** (string) - Required - Comma-separated list of chart types (e.g., 'most-played'). - **l** (string) - Optional - Localization language code (e.g., 'en-us'). ``` -------------------------------- ### Accessing MusicKit API v1 vs v3 Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=tech-notes-migrating-to-v3--page Demonstrates the API access change. In v1, API calls were made through `music.api`. In v3, the API method is a passthrough to the Apple Music API, requiring a full endpoint path. ```javascript music.api.album(1025210938) ``` ```javascript music.api.music('v1/catalog/{{storefrontId}}/albums/1025210938') ``` -------------------------------- ### MusicKit JS Set Queue (Playlist) Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Fhtml-embeds--html-embeds Sets the playback queue to a playlist using MusicKit JS. Requires a valid playlist identifier. ```javascript MusicKit.getInstance().setQueue({"contentType":"playlist","globalID":"1234567890"}); ``` -------------------------------- ### `playNext` Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page Inserts MediaItem(s) immediately after the currently playing item. ```APIDOC ## `playNext` ### Description Inserts the MediaItem(s) defined by `QueueOptions` immediately after the `nowPlayingItem` in the current `queue`. ### Method Signature `playNext(options: QueueOptions, clear?: Boolean): Promise` ### Parameters * `options` (QueueOptions) - See `QueueOptions` for more information. * `clear` (Boolean, Optional) - Optionally clear out the remaining queue items. Defaults to `false`. ### Return Value Returns a Promise that resolves with the updated `Queue`, or `void` if playback is not supported. ``` -------------------------------- ### Set Queue with Album ID Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-queue--page Sets the playback queue using an album ID and logs the media items in the queue. Ensure MusicKit is initialized before use. ```javascript const music = MusicKit.getInstance(); const queue = await music.setQueue({ album: '1025210938' }); console.log(queue.items); // log the MediaItems in the queue ``` -------------------------------- ### MusicKit JS Set Queue (Album) Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Fhtml-embeds--html-embeds Sets the playback queue to an album using MusicKit JS. Requires a valid album identifier. ```javascript MusicKit.getInstance().setQueue({"contentType":"album","globalID":"1234567890"}); ``` -------------------------------- ### Fetch Charts - MusicKit JS Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Fetch chart data. Requires a storefront ID and locale. Can specify chart types. ```javascript const queryParameters = { types: ['most-played'], l: 'en-us' }; await music.api.music(`/v1/catalog/{{storefrontId}}/charts`, queryParameters); ``` -------------------------------- ### Fetch Single Storefront Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Retrieves a single storefront using its unique identifier and an optional locale. ```APIDOC ## GET /v1/storefronts/{storefrontId} ### Description Fetches a storefront using its identifier. ### Method GET ### Endpoint /v1/storefronts/{storefrontId} ### Parameters #### Path Parameters - **storefrontId** (string) - Required - The identifier of the storefront to fetch. #### Query Parameters - **l** (string) - Optional - The locale for the storefront data (e.g., 'en-us'). ### Request Example ```json { "example": "const storefrontId = \'123456789\';\nconst queryParameters = { l: \'en-us\' };\nawait music.api.music(\\\/v1/storefronts/${storefrontId}\\\", queryParameters);" } ``` ### Response #### Success Response (200) - **data** (object) - The storefront object. #### Response Example ```json { "example": "{ // Storefront object }" } ``` ``` -------------------------------- ### playNext Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page&viewMode=story Inserts MediaItem(s) into the queue immediately following the currently playing item. Optionally, the rest of the queue can be cleared. ```APIDOC ## playNext ### Description Inserts the MediaItem(s) defined by `QueueOptions` immediately after the `nowPlayingItem` in the current `queue`. ### Method Not applicable (JavaScript method) ### Signature `playNext(options: QueueOptions, clear?: Boolean): Promise` ### Parameters #### Parameters - **options** (QueueOptions) - Required - See `QueueOptions` for more information. - **clear** (Boolean) - Optional - Default: `false` - Optionally clear out the remaining queue items. ### Return Value Returns a Promise that resolves with the updated `Queue`, or `void` if playback is not supported. ``` -------------------------------- ### playAt Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Freference-javascript-musickit-instance--page Inserts MediaItem(s) into the current queue at a specified position. ```APIDOC ## playAt ### Description Inserts the MediaItem(s) defined by `QueueOptions` at the position indicated in the current `queue`. ### Method `playAt(position: Number, options: QueueOptions): Promise` ### Parameters #### Path Parameters - **position** (Number) - Required - The index position in the `queue` to insert the new MediaItem(s) at. Position `0` is the first item in the `queue`. - **options** (QueueOptions) - Required - See `QueueOptions` for more information. ``` -------------------------------- ### Fetch Playlists - MusicKit JS Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Fetch one or more playlists using their identifiers. Requires a storefront ID and locale. ```javascript const queryParameters = { ids: ['1233456789', '987654321'], l: 'en-us' }; await music.api.music('/v1/catalog/{{storefrontId}}/playlists', queryParameters); ``` -------------------------------- ### Recommendations Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?path=%2Fstory%2Freference-javascript-api--page Fetch one or more recommendations using their identifiers. ```APIDOC ## GET /v1/me/recommendations ### Description Fetch one or more recommendations using their identifiers. ### Method GET ### Endpoint /v1/me/recommendations ### Parameters #### Query Parameters - **ids** (string[]) - Required - An array of recommendation identifiers. - **l** (string) - Optional - Localization parameter (e.g., 'en-us'). ### Request Example ```javascript const queryParameters = { ids: ['1233456789', '987654321'], l: 'en-us' }; await music.api.music(`/v1/me/recommendations`, queryParameters); ``` ``` -------------------------------- ### Fetch Music Videos - MusicKit JS Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Fetch one or more music videos using their identifiers. Requires a storefront ID and locale. ```javascript const queryParameters = { ids: ['1233456789', '987654321'], l: 'en-us' }; await music.api.music('/v1/catalog/{{storefrontId}}/music-videos', queryParameters); ``` -------------------------------- ### MusicKit JS Set Queue (Station) Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Fhtml-embeds--html-embeds Sets the playback queue to a station using MusicKit JS. Requires a valid station identifier. ```javascript MusicKit.getInstance().setQueue({"contentType":"station","globalID":"1234567890"}); ``` -------------------------------- ### MusicKitAPI.music() Method Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page The `api.music()` method facilitates making requests to the Apple Music API. It automatically appends the Developer Token (JWT) and Music User Token (MUT) for personalized requests, and can abstract the user's storefront from the URLs. ```APIDOC ## MusicKitAPI.music() ### Description Facilitates making requests to the Apple Music API by handling authentication headers and storefront abstraction. ### Method `async music(path, [queryParameters], [options])` ### Parameters #### Path Parameters * `path` (String) - **Required** - The path to the Apple Music API endpoint, without a hostname, and including a leading slash `/`. #### Query Parameters * `queryParameters` (Object) - **Optional** - An object with query parameters which will be appended to the request URL. The supported parameters vary by endpoint. #### Options * `options` (Object) - **Optional** - An object with additional options to control how requests are made. * `options.fetchOptions` (Object) - **Optional** - An object that is passed as options to the underlying `fetch()` function. ### Returns * Type: `Promise` * Properties: * `data` (Object) - The response body from the API request to the Apple Music API. ### Example ```javascript const music = MusicKit.getInstance(); // {{storefrontId}} is replaced with the current user’s storefront automatically const result = await music.api.music('/v1/catalog/{{storefrontId}}/albums/1025210938'); // Example with query parameters and destructuring response const queryParameters = { ids: ['123', '456'] }; const { data: { data: albums = [] } } = await music.api.music('/v1/catalog/{{storefront}}/albums', queryParameters); ``` ``` -------------------------------- ### Activity Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Fetch a single activity using its identifier. ```APIDOC ## Activity ### Description Fetch an activity using its identifier. ### Method GET ### Endpoint `/v1/catalog/{storefrontId}/activities/{activityId}` ### Parameters #### Path Parameters - **activityId** (string) - Required - The identifier of the activity to fetch. #### Query Parameters - **l** (string) - Optional - The locale for the request (e.g., 'en-us'). ``` -------------------------------- ### MusicKit Instance Properties Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page Properties of the MusicKit instance that can be accessed or modified. ```APIDOC ## MusicKit Instance Properties ### `api` **Type:** `MusicKitAPI` See Accessing Content via the Apple Music API for more information. ### `bitrate` **Type:** `MusicKit.PlaybackBitrate` The bit rate for the media player. Can be overridden by the app to a value from the enum `MusicKit.PlaybackBitrate`. Setting this property will affect the item played _next_. **Example** ```javascript const music = MusicKit.getInstance(); music.bitrate = MusicKit.PlaybackBitrate.HIGH; ``` ### `currentPlaybackDuration` **Type:** `Number` _read-only_ The duration of the `nowPlayingItem`, in seconds. ### `currentPlaybackProgress` **Type:** `Number` _read-only_ Progress percentage between `0` and `1` indicating the current play head position for the `nowPlayingItem`. ### `currentPlaybackTime` **Type:** `Number` _read-only_ The current position of the play head for the `nowPlayingItem`, in seconds. ### `currentPlaybackTimeRemaining` **Type:** `Number` _read-only_ The current remaining playback time for the `nowPlayingItem`, in seconds. ### `isAuthorized` **Type:** `Boolean` _read-only_ Indicates if the user has successfully signed in and authorized the application. ### `isPlaying` **Type:** `Boolean` _read-only_ Indicates whether the player is in the playing state. ### `nowPlayingItem` **Type:** `MediaItem` or `undefined` _read-only_ The `MediaItem` that is currently playing from the `Queue`. ### `nowPlayingItemIndex` **Type:** `Number` _read-only_ The index of the `nowPlayingItem` in the current playback `Queue`. ### `playbackRate` **Type:** `Number` The speed of playback. The default rate is `1.0`. ### `playbackState` **Type:** `MusicKit.PlaybackStates` _read-only_ The current playback state of the media player. ### `previewOnly` **Type:** `Boolean` Restricts MusicKit to playing only the preview assets, even when full playback is available. ### `queue` **Type:** `Queue` _read-only_ The current playback queue of the music player. ### `queueIsEmpty` **Type:** `Boolean` Indicates whether the current playback `queue` is empty. ### `repeatMode` **Type:** `MusicKit.PlayerRepeatMode` Controls the repeat behavior during playback. **Example** ```javascript const music = MusicKit.getInstance(); music.repeatMode = MusicKit.PlayerRepeatMode.all; ``` ``` -------------------------------- ### Fetch Multiple Recommendations by IDs Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Retrieve multiple recommendations by providing an array of their identifiers. Localization can be specified using the 'l' query parameter. ```javascript const queryParameters = { ids: ['1233456789', '987654321'], l: 'en-us' }; await music.api.music(`/v1/me/recommendations`, queryParameters); ``` -------------------------------- ### Set Preferred Bitrate for MusicKit Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-musickit-instance--page Instruct MusicKit to prefer high-bit rate assets when available. This affects the next item to be played, not the currently playing item. ```javascript const music = MusicKit.getInstance(); // Instruct MusicKit to prefer the high-bit rate assets, when available music.bitrate = MusicKit.PlaybackBitrate.HIGH; ``` -------------------------------- ### Fetch Activities Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page&viewMode=story Fetches one or more activities using their identifiers. ```APIDOC ## GET /v1/catalog/{storefrontId}/activities ### Description Fetches one or more activities using their identifiers. ### Method GET ### Endpoint /v1/catalog/{storefrontId}/activities ### Parameters #### Query Parameters - **ids** (string[]) - Required - A list of activity identifiers. - **l** (string) - Optional - The locale for the request. ``` -------------------------------- ### Fetch Multiple Storefronts Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page Retrieves one or more storefronts using their unique identifiers. You can specify multiple IDs and a locale for the results. ```APIDOC ## GET /v1/storefronts ### Description Fetches one or more storefronts using their identifiers. ### Method GET ### Endpoint /v1/storefronts ### Parameters #### Query Parameters - **ids** (string[]) - Required - A list of storefront identifiers to fetch. - **l** (string) - Optional - The locale for the storefront data (e.g., 'en-us'). ### Request Example ```json { "example": "const queryParameters = { ids: [\'1233456789\', \'987654321\'], l: \'en-us\' };\nawait music.api.music(\\\/v1/storefronts\\\", queryParameters);" } ``` ### Response #### Success Response (200) - **data** (array) - An array of storefront objects. #### Response Example ```json { "example": "[ // Array of storefront objects ]" } ``` ``` -------------------------------- ### Fetch Search Hints Source: https://js-cdn.music.apple.com/musickit/v3/docs/iframe.html?id=reference-javascript-api--page&viewMode=story Fetches search term suggestions based on a hint. ```APIDOC ## GET /v1/catalog/{storefrontId}/search/hints ### Description Fetches the search term results for a hint. ### Method GET ### Endpoint /v1/catalog/{storefrontId}/search/hints ### Parameters #### Query Parameters - **term** (string) - Required - The search hint term. - **l** (string) - Optional - The locale for the request. ``` -------------------------------- ### changeUserStorefront Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Freference-javascript-musickit-instance--page Changes the user's current storefront. This is useful for tailoring content recommendations and availability to a specific region. ```APIDOC ## changeUserStorefront ### Description Changes the user storefront. ### Method `changeUserStorefront(storefrontId: String): Promise` ### Parameters * `storefrontId` (String) - The `id` of the storefront to use as the `{{storefrontId}}` value in the `path` parameter of the Passthrough API method. ``` -------------------------------- ### playNext Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fdocs%2Freference-javascript-musickit-instance--page Inserts MediaItem(s) into the current queue immediately after the currently playing item. ```APIDOC ## playNext ### Description Inserts the MediaItem(s) defined by `QueueOptions` immediately after the `nowPlayingItem` in the current `queue`. ### Method `playNext(options: QueueOptions, clear?: Boolean): Promise` ### Parameters #### Path Parameters - **options** (QueueOptions) - Required - See `QueueOptions` for more information. - **clear** (Boolean) - Optional - Optionally clear out the remaining queue items. Default: `false`. ``` -------------------------------- ### MusicKit JS Controls - Playback Source: https://js-cdn.music.apple.com/musickit/v3/docs?path=%2Fstory%2Fhtml-embeds--html-embeds Includes buttons for controlling music playback: Play, Pause, and Stop. ```html ```