Skip to content

Web Playback SDK Reference

Important policy notes

Spotify.Player

Spotify.Player

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

Code Example:


_10
window.onSpotifyWebPlaybackSDKReady = () => {
_10
const token = '[My Spotify Web API access token]';
_10
const player = new Spotify.Player({
_10
name: 'Web Playback SDK Quick Start Player',
_10
getOAuthToken: cb => { cb(token); }
_10
});
_10
}

Parameter NameTypeDescriptionRequired
nameStringThe name of the Spotify Connect player. It will be visible in other Spotify appsRequired
getOAuthTokenFunctionThis 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 be provided with a callback parameter. You will need to execute this with a valid access_token string for a Spotify Premium user.Required
volumeFloatThe default volume of the player. Represented as a decimal between 0 and 1. Default value is 1.Optional
enableMediaSessionBooleanIf set to true, the Media Session API will be set with metadata and action handlers. Default value is false.Optional

Spotify.Player#connect

DescriptionConnect our Web Playback SDK instance to Spotify with the credentials provided during initialization.
ResponseReturns a Promise containing a Boolean (either true or false) with the success of the connection.

Code Example:


_10
player.connect().then(success => {
_10
if (success) {
_10
console.log('The Web Playback SDK successfully connected to Spotify!');
_10
}
_10
})

Spotify.Player#disconnect

DescriptionCloses the current session our Web Playback SDK has with Spotify.
ResponseVoid

Code Example:


_10
player.disconnect()

Spotify.Player#addListener

DescriptionCreate a new event listener in the Web Playback SDK. Alias for Spotify.Player#on.
ResponseReturns a Boolean. Returns true if the event listener for the event_name is unique. See #removeListener for removing existing listeners.

Code Example:


_10
player.addListener('ready', ({ device_id }) => {
_10
console.log('The Web Playback SDK is ready to play music!');
_10
console.log('Device ID', device_id);
_10
})

Parameter NameTypeDescriptionRequired
event_nameStringA valid event name. See Web Playback SDK Events.Required
callbackFunctionA callback function to be fired when the event has been executed.Required

Spotify.Player#removeListener

DescriptionRemove an event listener in the Web Playback SDK.
ResponseReturns a Boolean. Returns true if the event name is valid with registered callbacks from #addListener.

Code Example:


_10
// Removes all "ready" events
_10
player.removeListener('ready');
_10
// Remove a specific "ready" listener
_10
player.removeListener('ready', yourCallback)

Parameter NameTypeDescriptionRequired
event_nameStringA valid event name. See Web Playback SDK Events.Required
callbackFunctionThe callback function you would like to remove from the listener. If not provided, it will remove all callbacks under the event_name.Optional

Spotify.Player#getCurrentState

DescriptionCollect metadata on local playback.
ResponseReturns a Promise. It will return either a WebPlaybackState object or null depending on if the user is successfully connected.

Code Example:


_12
player.getCurrentState().then(state => {
_12
if (!state) {
_12
console.error('User is not playing music through the Web Playback SDK');
_12
return;
_12
}
_12
_12
var current_track = state.track_window.current_track;
_12
var next_track = state.track_window.next_tracks[0];
_12
_12
console.log('Currently Playing', current_track);
_12
console.log('Playing Next', next_track);
_12
});

Spotify.Player#setName

DescriptionRename the Spotify Player device. This is visible across all Spotify Connect devices.
ResponseReturns a Promise.

Code Example:


_10
player.setName("My New Player Name").then(() => {
_10
console.log('Player name updated!');
_10
});

Parameter NameTypeDescriptionRequired
nameStringThe new desired player name.Required

Spotify.Player#getVolume

DescriptionGet the local volume currently set in the Web Playback SDK.
ResponseReturns a Promise containing the local volume (as a Float between 0 and 1).

Code Example:


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

Spotify.Player#setVolume

DescriptionSet the local volume for the Web Playback SDK.
ResponseReturns an empty Promise

Code Example:


_10
player.setVolume(0.5).then(() => {
_10
console.log('Volume updated!');
_10
});

Parameter NameTypeDescriptionRequired
volumeFloatThe new desired volume for local playback. Between 0 and 1. Note: On iOS devices, the audio level is always under the user’s physical control. The volume property is not settable in JavaScript. Reading the volume property always returns 1. More details can be found in the iOS-specific Considerations documentation page by Apple.Required

Spotify.Player#pause

DescriptionPause the local playback.
ResponseReturns an empty Promise

Code Example:


_10
player.pause().then(() => {
_10
console.log('Paused!');
_10
});

Spotify.Player#resume

DescriptionResume the local playback.
ResponseReturns an empty Promise

Code Example:


_10
player.resume().then(() => {
_10
console.log('Resumed!');
_10
});

Spotify.Player#togglePlay

DescriptionResume/pause the local playback.
ResponseReturns an empty Promise

Code Example:


_10
player.togglePlay().then(() => {
_10
console.log('Toggled playback!');
_10
});

Spotify.Player#seek

DescriptionSeek to a position in the current track in local playback.
ResponseReturns an empty Promise

Code Example:


_10
// Seek to a minute into the track
_10
player.seek(60 * 1000).then(() => {
_10
console.log('Changed position!');
_10
});

Parameter NameTypeDescriptionRequired
position_msIntegerThe position in milliseconds to seek to.Required

Spotify.Player#previousTrack

DescriptionSwitch to the previous track in local playback.
ResponseReturns an empty Promise

Code Example:


_10
player.previousTrack().then(() => {
_10
console.log('Set to previous track!');
_10
});

Spotify.Player#nextTrack

DescriptionSkip to the next track in local playback.
ResponseReturns an empty Promise

Code Example:


_10
player.nextTrack().then(() => {
_10
console.log('Skipped to next track!');
_10
});

Spotify.Player#activateElement

DescriptionSome browsers prevent autoplay of media by ensuring that all playback is triggered by synchronous event-paths originating from user interaction such as a click. In the autoplay disabled browser, to be able to keep the playing state during transfer from other applications to yours, this function needs to be called in advance. Otherwise it will be in pause state once it’s transferred.
ResponseReturns an empty Promise

Code Example:


_10
myActivateElementButton.addEventListener('click', () => {
_10
// The player is activated. The player will keep the
_10
// playing state once the state is transferred from other
_10
// applications.
_10
player.activateElement();
_10
});
_10
// Transfer your currently playing track into your
_10
// application through device picker in Spotify APP.

Events

ready

DescriptionEmitted when the Web Playback SDK has successfully connected and is ready to stream content in the browser from Spotify.
ResponseReturns a WebPlaybackPlayer object.

Code Example:


_10
player.addListener('ready', ({ device_id }) => {
_10
console.log('Connected with Device ID', device_id);
_10
});

not_ready

DescriptionEmitted when the Web Playback SDK is not ready to play content, typically due to no internet connection.
ResponseReturns a WebPlaybackPlayer object.

Code Example:


_10
player.addListener('not_ready', ({ device_id }) => {
_10
console.log('Device ID is not ready for playback', device_id);
_10
});

player_state_changed

DescriptionEmitted when the state of the local playback has changed. It may be also executed in random intervals.
ResponseReturns a WebPlaybackPlayer object.

Code Example:


_10
player.addListener('player_state_changed', ({
_10
position,
_10
duration,
_10
track_window: { current_track }
_10
}) => {
_10
console.log('Currently Playing', current_track);
_10
console.log('Position in Song', position);
_10
console.log('Duration of Song', duration);
_10
});

autoplay_failed

DescriptionEmitted when playback is prohibited by the browser’s autoplay rules. Check Spotify.Player#activateElement for more information.
ResponseReturns null

Code Example:


_10
player.addListener('autoplay_failed', () => {
_10
console.log('Autoplay is not allowed by the browser autoplay rules');
_10
});

Errors

initialization_error

DescriptionEmitted 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 Example:


_10
player.on('initialization_error', ({ message }) => {
_10
console.error('Failed to initialize', message);
_10
});

authentication_error

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

Code Example:


_10
player.on('authentication_error', ({ message }) => {
_10
console.error('Failed to authenticate', message);
_10
});

account_error

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

Code Example:


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

playback_error

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

Code Example:


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

Objects

WebPlaybackPlayer Object

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


_10
{ device_id: "c349add90ccf047f4e737492b69ba912bdc55f6a" }

WebPlaybackState Object

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


_26
{
_26
context: {
_26
uri: 'spotify:album:xxx', // The URI of the context (can be null)
_26
metadata: {}, // Additional metadata for the context (can be null)
_26
},
_26
disallows: { // A simplified set of restriction controls for
_26
pausing: false, // The current track. By default, these fields
_26
peeking_next: false, // will either be set to false or undefined, which
_26
peeking_prev: false, // indicates that the particular operation is
_26
resuming: false, // allowed. When the field is set to `true`, this
_26
seeking: false, // means that the operation is not permitted. For
_26
skipping_next: false, // example, `skipping_next`, `skipping_prev` and
_26
skipping_prev: false // `seeking` will be set to `true` when playing an
_26
// ad track.
_26
},
_26
paused: false, // Whether the current track is paused.
_26
position: 0, // The position_ms of the current track.
_26
repeat_mode: 0, // The repeat mode. No repeat mode is 0,
_26
// repeat context is 1 and repeat track is 2.
_26
shuffle: false, // True if shuffled, false otherwise.
_26
track_window: {
_26
current_track: <WebPlaybackTrack>, // The track currently on local playback
_26
previous_tracks: [<WebPlaybackTrack>, <WebPlaybackTrack>, ...], // Previously played tracks. Number can vary.
_26
next_tracks: [<WebPlaybackTrack>, <WebPlaybackTrack>, ...] // Tracks queued next. Number can vary.
_26
}
_26
}

WebPlaybackTrack Object

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


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

WebPlaybackError 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:


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