Question

I am having difficulties with both Toplists and Image right now and I am hoping that someone can help me. Essentially, all I want to do is create a player and playlist with an artists top tracks. I have tried using search since I can't get the desired behaviour out of Toplists, but that hasn't bought me any closer so I thought I'd ask here.

Essentially, the functionality should:

  1. Take an artist name or artist id
  2. Find that artists top 10 tracks
  3. Create a new temporary playlist and add the 10 tracks
  4. Create and insert a player and a playlist

This would seem pretty easy, but it's driving me a little nuts.

Was it helpful?

Solution

You can use the Toplist.forArtist function for fetching the top 10 tracks by an artist.

The following code fetches the first 10 top tracks for an artist and renders a list view and a player:

require(['$api/toplists#Toplist', '$views/list#List', '$views/image#Image'],
  function(Toplist, List, Image) {

  var artist = models.Artist.fromURI('spotify:artist:2qk9voo8llSGYcZ6xrBzKx');
  var toplist = Toplist.forArtist(artist);

  // fetch the 10 most played tracks
  toplist.tracks.snapshot(0, 10).done(function(tracks) {

    // create temporary playlist
    models.Playlist
      .createTemporary('myTempList')
      .done(function(playlist){ 
        playlist.load('tracks').done(function(){
          for (var i = 0, l = tracks.length; i < l; i++) {
              var track = tracks.get(i);
              playlist.tracks.add(track);
          }

          // append a list view
          var listWrapper = document.getElementById('list-wrapper');
          var list = List.forPlaylist(playlist);
          listWrapper.appendChild(list.node);
          list.init();

          // append a player
          // note that you might have a grey placeholder
          // see https://stackoverflow.com/questions/17477655
          var playerWrapper = document.getElementById('player-wrapper');
          var player = Image.forPlaylist(playlist, {player: true});
          playerWrapper.appendChild(player.node);
      });
    });
  });
});

The JS code refers to 2 placeholders that will contain the views:

    <div id="list-wrapper"></div>
    <div id="player-wrapper"></div>

Note that due to a problem with mosaic cover images for temporary playlist you may need to replace the default cover placeholder with another image.

OTHER TIPS

Unfortunately, it appears you'll have to brute-force it.

  • Get all tracks by the artist, either by:
    • iterating all of the Artist's albums, appearances, compilations, singles and collecting all the tracks
    • Use the poorly-documented-but-probably-easy-to-guess Search module and search for the artist, hopefully getting all their tracks. Here's the advanced search docs
  • Retrieve the popularity of all the tracks
  • Find the ten highest popularity tracks
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top