Domanda

I would like to know if there's a way to know which playlist is currently playing on spotify. I have read the API and found a "isLoaded" function, which returns a boolean. I could go through all the playlists and get which one is the one loaded, but I would like to know if there is a way to do this more directly.

È stato utile?

Soluzione

You can find out the uri of the context of what is playing in the Player using:

require([
  '$api/models',
], function(models) {
  'use strict';

  // find out initial status of the player
  models.player.load(['context']).done(function(player) {
    // player.context.uri will contain the uri of the context
  });

  // subscribe to changes
  models.player.addEventListener('change', function(m) {
    // m.data.context.uri will contain the uri of the context
  });
});

You can use that uri to fetch properties, such as the name. In the following example we retrieve the name of the playlist if the current track's context is a playlist:

require([
  '$api/models',
], function(models) {
  'use strict';

  /**
   * Returns whether the uri belongs to a playlist.
   * @param {string} uri The Spotify URI.
   * @return {boolean} True if the uri belongs to a playlist, false otherwise.
   */
  function isPlaylist(uri) {
    return models.fromURI(uri) instanceof models.Playlist;
  }

  /**
   * Returns the name of the playlist.
   * @param {string} playlistUri The Spotify URI of the playlist.
   * @param {function(string)} callback The callback function.
   */
  function getPlaylistName(playlistUri, callback) {
    models.Playlist.fromURI(models.player.context.uri)
      .load('name')
      .done(function(playlist){
        callback(playlist.name);
    });
  }

  // find out initial status of the player
  models.player.load(['context']).done(function(player) {
    var uri = player.context.uri;
    if (isPlaylist(uri)) {
      getPlaylistName(player.context.uri, function(name) {
        // do something with 'name'
      });
    }
  });

  // subscribe to changes
  models.player.addEventListener('change', function(m) {
    var uri = m.data.context.uri;
    if (isPlaylist(uri)) {
      getPlaylistName(m.data.context.uri, function(name) {
        // do something with 'name'
      });
    }
  });
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top