Photo by Sergi Kabrera on Unsplash

Spotify provides developers an easy way to create music streaming apps through their web playback SDK. This javascript library offers developers all of the necessary tools using Spotify connect to stream music on their app. This library is intended to be used in conjunction with Spotify’s OAuth and web API. Once a user has authenticated and received a Spotify ID and access token the Web API returns URIs from which to stream the music. In addition to playback functionality, the SDK allows the developer’s app to collect metadata for the tracks being listened to and the user’s listening session directly.

Management of the SDK in the browser uses a combination of listeners and callback functions tied to events. These events can either control the client-side playback or the playback on another Spotify-connected app. Initializing the SDK starts in your index.html file with the addition of the playback SDK library within a script tag. On loading your site you must define the onSpotifyWebPlaybackSDKReady method to initialize the SDK once the Spotify payer is ready to load your code.

<script src="https://sdk.scdn.co/spotify-player.js"></script>
window.onSpotifyWebPlaybackSDKReady = () => {
const play = ({
spotify_uri,
playerInstance: {
_options: {
getOAuthToken,
id
}
}
}) => {
getOAuthToken(access_token => {
fetch(`https://api.spotify.com/v1/me/player/play? device_id=${id}`, {
method: 'PUT',
body: JSON.stringify({ uris: [spotify_uri] }),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
},
});
});
};

play({
playerInstance: new Spotify.Player({ name: "..." }),
spotify_uri: 'spotify:track:7xGfFoTpQ2E7fRF5lN10tr',
});
};

In the above code, we must supply our Client ID to successfully receive an authorization token to access Spotify’s API. This ID, along with a secret ID, is provided when you register your app with Spotify. At the bottom, the new player is being. Once the above play function is created and proper authorization is achieved, it can be used in conjunction with the Spotify API to stream Spotify Audio in the browser. When the play function is invoked it is passed parameters of a newly generated instance and a URI. The spotify_uri property represents the URI the developer’s app will be streaming the data from.

The next step is to initialize the SDK with the constructor Spotify.Player and passing the argument of an object containing the name of the player, a callback containing the access token, and a default volume level. The name of the player is what the client will be visible as in the user’s other Spotify apps.

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
});

In the app’s current configuration the only way to control the payback in the browser is to connect to the developer’s app in the Spotify app to give commends to the client. At this point, if our intention is to control the player in the browser we will require listener functions to handle the state of the playback. Some examples of events to be listened for are ready, not_ready, and player_state_changed. The below listener example listeners for the ‘ready’ state and uses the provided callback function to log the device_id and confirmation the player is connected.

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

Finally, the Spotify API can be used to remotely control the user’s other Spotify apps but controlling functionality like seeking, volume, and track selection. The first example shows the process of setting the volume of a remotely connected player. The asynchronous method Spotify.setVolume takes a value to set the volume. The second method returns the state of the remote player and the subsequent destructuring of the response from the Spotify API.

player.setVolume(0.5).then(() => {   console.log('Volume updated!'); });player.getCurrentState().then(state => {
if (!state) {
console.error('User is not playing music through the Web Playback SDK');
return;
}

let {
current_track,
next_tracks: [next_track]
} = state.track_window;

console.log('Currently Playing', current_track);
console.log('Playing Next', next_track);
});