SDK Reference

Initializing the SDK

In order to initialize the Web Playback SDK, you need to embed a single line of JavaScript inside of your application. It should belong inside the <body> tag:

<script src="https://sdk.scdn.co/spotify-player.js"></script>

You are then required to define a window.onSpotifyWebPlaybackSDKReady method immediately. This will be executed once the Web Playback SDK has successfully loaded and the Spotify.Player is available to load the SDK.

<script>
window.onSpotifyWebPlaybackSDKReady = () => {
  // You can now initialize Spotify.Player and use the SDK
};
</script>

API Reference

Spotify.Player

Description

The main constructor for initializing the Web Playback SDK. It should contain an object with the player name, volume and access token.

Response

Void

Code Sample
var player = new Spotify.Player({
  name: "Carly Rae Jepsen Player",
  getOAuthToken: callback => {
    // Run code to get a fresh access token
    callback("access token here");
  },
  volume: 0.5
});
Parameter Name Type Description Required
name String The name of the Spotify Connect player. It will be visible in other Spotify apps. Required
getOAuthToken Function This will be called every time you run Spotify.Player#connect or when a user's access token has expired (maximum of 60 minutes).

You will need to execute the callback with a valid access token for a Spotify Premium user. It should be provided in the form of a String.
Required
volume Float The default volume of the player. Represented as a decimal between 0 and 1. Default value is 1. Optional

Spotify.Player#connect

Description

Connect our Web Playback SDK instance to Spotify with the credentials provided during initialization.

Response

Returns a Promise containing a Boolean (either true or false) with the success of the connection.

Code Sample
player.connect().then(success => {
  if (success) {
    console.log("The Web Playback SDK successfully connected to Spotify!")
  }
})

Spotify.Player#disconnect

Description

Closes the current session our Web Playback SDK has with Spotify.

Response

Void

Code Sample
player.disconnect()

Spotify.Player#on

Description

Create a new event listener in the Web Playback SDK.

Response

Void

Code Sample
player.on("ready", data => {
  let { device_id } = data;
  console.log("The Web Playback SDK is ready to play music!");
  console.log("Device ID", device_id);
})
Parameter Name Type Description Required
event_name String A valid event name. See Web Playback SDK Events. Required
callback Function A callback function to be fired when the event has been executed. Required

Spotify.Player#getCurrentState

Description

Collect metadata on local playback.

Response

Returns a Promise. It will return either a PlaybackState object or null depending on if the user is successfully connected.

Code Sample
player.getCurrentState().then(state => {
  if (state) {
    let { current_track, next_tracks } = state.track_window;

    console.log("Currently Playing", current_track);
    console.log("Playing Next", next_tracks[0]);
  } else {
    console.error("The user is not playing music through the Web Playback SDK");
  }
});

Spotify.Player#getVolume

Description

Get the local volume currently set in the Web Playback SDK.

Response

Returns a Promise containing the local volume (as a Float between 0 and 1).

Code Sample
player.getVolume().then(volume => {
  let volume_percentage = volume * 100;
  console.log(`The volume of the player is ${volume_percentage}%`);
});

Spotify.Player#setVolume

Description

Set the local volume for the Web Playback SDK.

Response

Returns an empty Promise.

Code Sample
player.setVolume(0.5).then(() => {
  console.log("Volume updated!");
});
Parameter Name Type Description Required
volume Float The new desired volume for local playback. Between 0 and 1. Required

Spotify.Player#pause

Description

Pause the local playback.

Response

Returns an empty Promise.

Code Sample
player.pause().then(() => {
  console.log("Paused!");
});

Spotify.Player#resume

Description

Resume the local playback.

Response

Returns an empty Promise.

Code Sample
player.resume().then(() => {
  console.log("Resumed!");
});

Spotify.Player#togglePlay

Description

Resume/pause the local playback.

Response

Returns an empty Promise.

Code Sample
player.togglePlay().then(() => {
  console.log("Toggled playback!");
});

Spotify.Player#seek

Description

Seek to a position in the current track in local playback.

Response

Returns an empty Promise.

Code Sample
// Seek to a minute into the track
player.seek(60 * 1000).then(() => {
  console.log("Changed position!");
});
Parameter Name Type Description Required
position_ms Integer The position in milliseconds to seek to. Required

Spotify.Player#previousTrack

Description

Switch to the previous track in local playback.

Response

Returns an empty Promise.

Code Sample
player.previousTrack().then(() => {
  console.log("Set to previous track!");
});

Spotify.Player#nextTrack

Description

Skip to the next track in local playback.

Response

Returns an empty Promise.

Code Sample
player.nextTrack().then(() => {
  console.log("Skipped to next track!");
});

Events

ready

Description

Emitted when the Web Playback SDK has successfully connected and is ready to stream content in the browser from Spotify.

Response

Returns a WebPlaybackInstance object.

Code Sample
player.on("ready", data => {
  let { device_id } = data;
  console.log("Connected with Device ID", device_id);
});

player_state_changed

Description

Emitted when the state of the local playback has changed. It may be also executed in random intervals.

Response

Returns a PlaybackState object.

Code Sample
player.on("player_state_changed", state => {
  let {
    position,
    duration,
    track_window: { current_track }
  } = state;

  console.log("Currently Playing", current_track);
  console.log("Position in Song", position);
  console.log("Duration of Song", duration);
});

Error Reference

initialization_error

Description

Emitted when the Spotify.Player fails to instantiate a player capable of playing content in the current environment. Most likely due to the browser not supporting EME protection.

Code Sample
player.on('initialization_error', (e) => {
  console.error("Failed to initialize", e.message);
});

authentication_error

Description

Emitted when the Spotify.Player fails to instantiate a valid Spotify connection from the access token provided to getOAuthToken.

Code Sample
player.on('authentication_error', (e) => {
  console.error("Failed to authenticate", e.message);
});

account_error

Description

Emitted when the user authenticated does not have a valid Spotify Premium subscription.

Code Sample
player.on('account_error', (e) => {
  console.error("Failed to validate Spotify account", e.message);
});

playback_error

Description

Emitted when loading and/or playing back a track failed.

Code Sample
player.on('playback_error', (e) => {
  console.error("Failed to perform playback", e.message);
});

Objects

PlaybackState Object

This is an object that is provided every time Spotify.Player#getCurrentState is called. It contains information on context, permissions & restrictions, playback state, the user’s session, and more.

{
  context: {
    uri: 'spotify:album:xxx', // The URI of the context (can be null)
    metadata: {},             // Additional metadata for the context (can be null)
  },
  disallows: {                // A simplified set of restriction controls for
    pausing: false,           // The current track. By default, these fields
    peeking_next: false,      // will either be set to false or undefined, which
    peeking_prev: false,      // indicates that the particular operation is
    resuming: false,          // allowed. When the field is set to `true`, this
    seeking: false,           // means that the operation is not permitted. For
    skipping_next: false,     // example, `skipping_next`, `skipping_prev` and
    skipping_prev: false      // `seeking` will be set to `true` when playing an
                              // ad track.
  },
  paused: false,  // Whether the current track is paused.
  position: 0,    // The position_ms of the current track.
  repeat_mode: 0, // The repeat mode. No repeat mode is 0,
                  // once-repeat is 1 and full repeat is 2.
  shuffle: false, // True if shuffled, false otherwise.
  restrictions: {                       // This map can be used to figure out
    disallow_pausing_reasons: [],       // the exact reason why a `disallows`
    disallow_peeking_next_reasons: [],  // field is set to true. Each field
    disallow_peeking_prev_reasons: [],  // contains an array of strings that
    disallow_resuming_reasons: [],      // detail why a particular operation
    disallow_seeking_reasons: [],       // is disallowed. For example, if
    disallow_skipping_next_reasons: [], // `disallows.seeking` is set to true,
    disallow_skipping_prev_reasons: []  // then `disallow_seeking_reasons`
                                        // will contain a string saying why
                                        // seeking is disallowed (e.g.,
                                        // `['because_ad']`.
  },
  track_window: {
    current_track: <Track>,                   // The track currently on local playback
    previous_tracks: [<Track>, <Track>, ...], // Previously played tracks. Number can vary.
    next_tracks: [<Track>, <Track>, ...]      // Tracks queued next. Number can vary.
  }
}

Track Object

This is an object that is provided inside track_window from the PlaybackState Object. Track objects are Spotify Web API compatible objects containing metadata on Spotify content.

{
  uri: "spotify:track:xxxx", // Spotify URI
  id: "xxxx",                // Spotify ID from URI (can be null)
  type: "track",             // Content type: can be "track", "episode" or "ad"
  media_type: "audio",       // Type of file: can be "audio" or "video"
  name: "Song Name",         // Name of content
  is_playable: true,         // Flag indicating whether it can be played
  album: {
    uri: 'spotify:album:xxxx', // Spotify Album URI
    name: 'Album Name',
    images: [
      { url: "https://image/xxxx" }
    ]
  },
  artists: [
    { uri: 'spotify:artist:xxxx', name: "Artist Name" }
  ]
}

WebPlaybackInstance Object

This is an object that is provided in the ready event as an argument. WebPlaybackInstance objects contain information related to the current instance of the Web Playback SDK.

{ device_id: "c349add90ccf047f4e737492b69ba912bdc55f6a" }

Error Object

This is an object that is provided in all error handlers from the Web Playback SDK. It is referred to as e and looks like this:

{ message: "This will contain a message explaining the error." }