4.5 - Music-player
Last updated
Was this helpful?
Last updated
Was this helpful?
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 music player is powered by the this is as stated by Spotify:
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:
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:
which fires the start function: