The goal of the music player is that users can click on a track and the music player starts playing the chosen track:
It's also possible for users to scrub through the track, and adjust the volume. The challenge With the music players is that is had to be accessible form every page on the app, and it should keep the current state.
The Web Playback SDK is client-side JavaScript library which allows you to create a new player in Spotify Connect and play any audio track from Spotify in the browser via Encrypted Media Extensions.
The SDK is initialized under the link to the library, this is done by setting the onSpotifyWebPlaybackSDKReady event which is triggered in the following manner:
window.onSpotifyWebPlaybackSDKReady=()=>{consttoken='[My Spotify Web API access token]';constplayer=newSpotify.Player({name:'Ringo Pro Player',getOAuthToken:cb=>{cb(token);}}); // Connect to the player!player.connect();};
Within this event you can trigger other events, the ones we used are:
getCurrentState
``js player.getCurrentState().then(state => { if(!state){ // nowPlaying.children[0].textContent = 'Click on a song!' // console.error('User is not playing music through the Web Playback SDK') console.log('User is not playing music through the Web Playback SDK') fetch('https://api.spotify.com/v1/me/player', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization':Bearer ${token}` }}) .then(res => res.json()) .then(body => { console.log(body) nowPlaying.children[0].textContent = body.item.name nowPlaying.children[1].textContent = body.item.artists[0].name
setVolume:
togglePlay:
seek:
In order to play the track an eventListener is added to the each track's album image: