0
votes

I've integrated web playback SDK of Spotify on my website allowing my users to login via their spotify accounts and play music.

However, the issue is, music gets played as soon as page is loaded. I want this to happen when the play button is hit.

Here's the JS code I've written

/**
 * Convert milliseconds to minutes
 */
function millisToMinutesAndSeconds(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

jQuery( document ).ready(function() {
    console.log( "ready!" );
});

/**
 * Callback for Spotify when SDK is ready
 */
window.onSpotifyWebPlaybackSDKReady = () => {
  const player = new Spotify.Player({
    name: 'Web Playback SDK Quick Start Player',
    getOAuthToken: cb => { cb(token); },
    volume: 0.8
  });
  var setintId = 0;
  var progressMs = 0;
  var progressBar = jQuery('#song-progress .noUi-origin');
  // Playback status updates
  player.addListener('player_state_changed', state => {
      if (state != null) {
          jQuery('.current-track__progress__finish').text(millisToMinutesAndSeconds(state.duration));
          if (state.paused) {
              jQuery('.current-track').find('.play').addClass('ion-ios-play').removeClass('ion-ios-pause');
          } else {
              jQuery('.current-track').find('.play').addClass('ion-ios-pause').removeClass('ion-ios-play');
          }
          clearInterval(setintId);
          progressMs = state.position;
          // progress bar logic
          if (state.paused == false) {
              setintId = setInterval(function (state) {
                  progressMs += 1000;
                  let progressPercentage = progressMs / state.duration * 100;
                  document.getElementById('song-progress').noUiSlider.set(progressPercentage);

                  //progressBar.css('left',progressPercentage.toFixed(1) + '%');
                  jQuery('.current-track__progress__start').text(millisToMinutesAndSeconds(progressMs));
                  if (progressMs >= state.duration) {
                      clearInterval(setintId);
                  }
              }, 1000, state);
          }
      }
  });

    // Seek to a minute into the track
    progressBar.find('.noUi-handle').on('mousedown',function(){
        clearInterval(setintId);
    });
    progressBar.find('.noUi-handle').on('mouseup',function(){
        player.getCurrentState().then(state => {
              if (!state) {
                console.error('User is not playing music through the Web Playback SDK');
                return;
              }
                var percentage = parseInt(progressBar.css('left')) /  parseInt(progressBar.parent().width()) * 100;
                document.getElementById('song-progress').noUiSlider.set(percentage);
                var seekTo = ( parseInt( percentage ) / 100 ) * state.duration;
                player.seek(seekTo).then(() => {
                  console.log('Changed position!');
                });
        });
    });

  // Error handling
  player.addListener('initialization_error', ({ message }) => { alert(message); });
  player.addListener('authentication_error', ({ message }) => { alert(message); });
  player.addListener('account_error', ({ message }) => { alert(message); });
  player.addListener('playback_error', ({ message }) => { alert(message); });


  // Ready
  player.addListener('ready', ({ device_id }) => {
        var playerSkin = jQuery('.current-track');
        var trackList  = jQuery('.tracks');
        var tracks = [];

        if (typeof search_artist !== "undefined") {
            fetch('https://api.spotify.com/v1/search/?q=' + search_artist + '&type=artist', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + token
                },
            }).then(function(response) {
                return response.json();
            }).then((response)=>{
                var artists = response.artists;
                var firstItemId = artists.items[0].id;
                getTopTenTracks(firstItemId);
            }).catch((error)=>{
                console.log('error',error);
            });
        }

        function getTopTenTracks(artistID) {
            fetch('https://api.spotify.com/v1/artists/'+ artistID +'/top-tracks?market=from_token', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + token
                },
            }).then(function(response) {
                return response.json();
            }).then((response)=>{
                var tracksGot = response.tracks;
                parseTracksList(tracksGot);
                trackList  = jQuery('.tracks');
                trackList.find('.track').each(function(){
                    tracks.push(jQuery(this).data('uri'));
                });

                // setUpListeners();
                fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
                    method: 'PUT',
                    body: JSON.stringify({uris: tracks}),
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    },
                }).then(function (response) {
                    setUpListeners();
                });
            }).catch((error)=>{
                console.log('error',error);
            });
        }

        function parseTracksList(tracks) {
            for (var i = 0; i < tracks.length; i++) {
                appendTrackToHtml(tracks[i],i);
            }
        }

        var artistContent = document.getElementById('search_artist_content');

        function appendTrackToHtml(track, iterator) {
            var wrapper = document.createElement('div');
            wrapper.className='tracks songTrack';
            var trackDiv = document.createElement('div');
            trackDiv.className = 'track';
            trackDiv.setAttribute('data-uri',track.uri);

            var imgWrapper = document.createElement('div');
            imgWrapper.className = 'track__art';
            var trackArt = document.createElement("img");
            trackArt.src = track.album.images[2].url;
            imgWrapper.appendChild(trackArt);
            trackDiv.appendChild(imgWrapper);

            var counter = document.createElement('div');
            counter.className = 'track__number';
            counter.append(iterator);
            trackDiv.append(counter);

            var checkMarkWrap = document.createElement('div');
            checkMarkWrap.className = 'track__added';
            var icon = document.createElement('i');
            icon.className = 'ion-checkmark-round added';
            checkMarkWrap.appendChild(icon);
            trackDiv.appendChild(checkMarkWrap);

            var trackTitle = document.createElement('div');
            trackTitle.className = 'track__title';
            trackTitle.append(track.name);
            trackDiv.appendChild(trackTitle);

            wrapper.appendChild(trackDiv);
            artistContent.appendChild(wrapper);
        }

        if (typeof search_artist === "undefined") {
            trackList.find('.track').each(function(){
                tracks.push(jQuery(this).data('uri'));
            });

            //Start to play
            fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
                method: 'PUT',
                body: JSON.stringify({uris: tracks}),
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + token
                },
            });

            setUpListeners();
        }

        function setUpListeners() {

            // Change track from OverView list
            trackList.on('click','.track',function(){

                fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
                    method: 'PUT',
                    body: JSON.stringify({ uris: [jQuery(this).data('uri')] }),
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    },
                });

            });

            // Start to play all tracks by clicking play button of artist
            jQuery('.artist__info__actions button.button-dark').on('click', function () {

                fetch('https://api.spotify.com/v1/me/player/play?device_id=' + device_id, {
                    method: 'PUT',
                    body: JSON.stringify({uris: tracks}),
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    },
                });

            });


            //Play button
            playerSkin.find('.play').on('click', function () {
                jQuery(this).toggleClass('ion-ios-play ion-ios-pause');
                console.log('play clicked');
                player.togglePlay().then(() => {
                    console.log('Toggled playback!');
                });
            });

            //Volume button
            playerSkin.find('#song-volume .noUi-origin').on('mouseup', function () {
                let width = parseInt(playerSkin.find('#song-volume .noUi-base').width());
                let volume = parseInt(jQuery(this).css('left')) / width;

                player.setVolume(volume.toFixed(1)).then(() => {
                    // Switch buttons
                    if (volume == 0) {
                        playerSkin.find('.control.volume i').addClass('ion-volume-mute').removeClass('ion-volume-hight');
                    } else {
                        playerSkin.find('.control.volume i').addClass('ion-volume-hight').removeClass('ion-volume-mute');
                    }
                });
            });

            //Mute button
            playerSkin.on('click', '.control.volume i.ion-volume-high', function () {
                player.setVolume(0).then(() => {
                    playerSkin.find('.control.volume i').addClass('ion-volume-mute').removeClass('ion-volume-high');
                    playerSkin.find('#song-volume .noUi-origin').css('left', '0%');
                });
            });

            //Unmute button
            playerSkin.on('click', '.control.volume i.ion-volume-mute', function () {
                player.setVolume(0.5).then(() => {
                    playerSkin.find('.control.volume i').addClass('ion-volume-high').removeClass('ion-volume-mute');
                    playerSkin.find('#song-volume .noUi-origin').css('left', '50%');
                });
            });

            // Next track
            playerSkin.find('.ion-ios-skipforward').on('click', function () {
                player.nextTrack().then(() => {
                    console.log('Skipped to next track!');
                });
            });


            //Prev track
            playerSkin.find('.ion-ios-skipbackward').on('click', function () {
                player.previousTrack().then(() => {
                    console.log('Set to previous track!');
                });
            });

            // Change position and Duration
            player.addListener('player_state_changed', ({
                                                            position,
                                                            duration,
                                                            track_window: {current_track}
                                                        }) => {
                jQuery('.playing__song__name').text(current_track.name);
                jQuery('.playing__song__artist').text(current_track.artists[0].name);
                jQuery('.playing__art img').attr('src', current_track.album.images[0].url);
                //Set active item in list
                trackList.find('.track').removeClass('playing');
                trackList.find('[data-uri="' + current_track.uri + '"]').addClass('playing');
            });
        }

  });

  // Connect to the player!
  player.connect();
};

Any guidance would be appreciated.

1
I'm currently stuck on the exact same problem for iOS, so interested to hear from anyone if this possible on any of the APIs.Benjamin Lowry

1 Answers

0
votes

Took a look through and it seems to be a problem with your code and not with the SDK itself.

In the player.addListener('ready') block (which will be called automatically when the player is initialised), you have a line, if (typeof search_artist !== "undefined") and another checking if it's undefined. I can't know exactly what's happening without seeing the code where search_artist is defined, but both paths eventually call https://api.spotify.com/v1/me/player/play, resulting in the play you're hearing.

If you want play to happen on click of a button, you should make a separate function for it instead of calling it in a callback.