How to access audio features from Spotify Player JS library

Viewed 70

I'm trying to use this spotify player js library to access the audio features of a currently playing song. I don't know how I should use the endpoint in my code to get the audio features (such as valence and energy) to print in my console. Right now, it just displays the name of the song and the artist when I play the song on my laptop. Here is the code that I have based on this one codepen that the person who made the library made for demo.

var mainContainer = document.getElementById('js-main-container'),
    loginContainer = document.getElementById('js-login-container'),
    loginButton = document.getElementById('js-btn-login'),

var spotifyPlayer = new SpotifyPlayer();

var template = function (data) {
  return `
    <div class="main-wrapper">
      <div class="now-playing__side">
        <div class="now-playing__name">${data.item.name}</div>
        <div class="now-playing__artist">${data.item.artists[0].name}</div>
      </div>
    </div>
  `;
};

var artistsCache = {},
    artistFetching = false;
spotifyPlayer.on('update', response => {
  var mainArtist = response.item.artists[0];
  if (!(mainArtist.id in artistsCache) && !artistFetching) {
    artistFetching = true;
    spotifyPlayer.fetchGeneric(mainArtist.href)
      .then(function(artist) {
        artistFetching = false;
        return artist.json();
      }).then(function(artist) {
        if (artist.images.length) {
          artistsCache[artist.id] = artist.images[0].url;
        }
      }).catch(function(e) {
        artistFetching = false;
      });
  }
  mainContainer.innerHTML = template(response);
});

spotifyPlayer.on('login', user => {
  if (user === null) {
    loginContainer.style.display = 'block';
    mainContainer.style.display = 'none';
  } else {
    loginContainer.style.display = 'none';
    mainContainer.style.display = 'block';
  }
});

loginButton.addEventListener('click', () => {
    spotifyPlayer.login();
});

spotifyPlayer.init();
0 Answers
Related