簡體   English   中英

Spotify javascript API - 獲取播放列表中歌曲的類型

[英]Spotify javascript API - getting the genre of a song in a playlist

我目前正在使用非常酷的應用程序 Exportify ( https://github.com/watsonbox/exportify ) 將 Spotify 播放列表導出到 CSV。

我的 javascript 知識很糟糕,但我目前正在嘗試包含每首曲目的類型,但我無法檢索它。

我假設:

我可以通過添加來獲取藝術家 ID

item.track.artists.map(function (artist) {
  return artist.id
}).join(', '),

exportify.js文件中的以下代碼。

var tracks = responses.map(function (response) {
  return response.items.map(function (item) {
    return [
      item.track.uri,
      item.track.id,
      item.track.name,
      item.track.artists.map(function (artist) {
        return artist.name
      }).join(', '),
      item.track.artists.map(function (artist) {
        return artist.id
      }).join(', '),
      item.track.album.name,
      item.track.disc_number,
      item.track.track_number,
      item.track.duration_ms,
      item.added_by == null ? '' : item.added_by.uri,
      item.added_at
    ].map(function (track) {
      return '"' + track + '"';
    })
  });
});

誰能告訴我如何根據藝術家 ID 獲取藝術家類型並將其添加為另一列?

謝謝

克里斯

在 Spotify 中使用“Get an Artist”端點:

https://developer.spotify.com/web-api/get-artist/

調用此端點將為您提供給定藝術家 ID 的藝術家的流派。

正如 Potray 所說,您可以連接到端點 getArtist。 更具體地說,返回的 JSON 將有一個流派鍵。 流派鍵直接指向流派數組。

response.genres 將訪問這個數組。

您可以在此處的 RapidAPI 上對此進行測試 我專門將您鏈接到 getArtist 端點。 在這里你可以填寫artist_id,點擊測試,然后看到一個示例響應。 RapidAPI 還將生成一個代碼片段,因此您可以直接將 API 調用復制並粘貼到您自己的代碼中。

在這里,我正在使用 Red Hot Chili Peppers Artist_id "0L8ExT028jH3ddEcZwqJJ5" 測試 getArtist 端點:

在此處輸入圖片說明

您會注意到流派數組包含 5 個項目:['alternative rock', 'funk metal', 'funk rock', 'permanent wave', 'rock' ]

如果您直接單擊右側響應的 CODE 並登錄,您將能夠訪問代碼片段,並將其直接粘貼到您的代碼中。 一個例子是:

在此處輸入圖片說明

請注意此處引用的流派與您在大多數 api 中實際遇到的流派不匹配(例如,與track.artist.genres不匹配)

https://developer.spotify.com/console/get-available-genre-seeds/

這個問題很突出: https : //github.com/spotify/web-api/issues/410

我已經實施了!

下面是來自https://github.com/pavelkomarov/exportify/blob/master/exportify.js的函數,它進行所有必需的 API 查詢。 我的apiCall函數也在該文件中。 它正在使用fetch

  1. 首先,我從播放列表中發送對大量歌曲的請求。
  2. 然后我將這些消息聚合到一個數據表和一組藝術家中。
  3. 然后我使用藝術家集來查詢流派信息。
  4. 然后我將其加入數據並寫出到 csv。

因為這一切都發生在網絡上,所以每個新步驟都必須包含在.then() ,這取決於之前的對象得到解決。 值得慶幸的是,近年來 JavaScript 在這方面變得更加優雅。 https://eloquentjavascript.net/11_async.html

實時應用程序住在這里 我還創建了一個筆記本來分析輸出。

csvData(access_token, playlist) {
    // Make asynchronous API calls for 100 songs at a time, and put the results (all Promises) in a list.
    let requests = [];
    for (let offset = 0; offset < playlist.tracks.total; offset = offset + 100) {
        requests.push(utils.apiCall(playlist.tracks.href.split('?')[0] + '?offset=' + offset + '&limit=100',
                access_token));
    }

    // "returns a single Promise that resolves when all of the promises passed as an iterable have resolved"
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
    let artist_hrefs = new Set();
    let data_promise = Promise.all(requests).then(responses => {
        return responses.map(response => { // apply to all responses
            return response.items.map(song => { // appy to all songs in each response
                song.track.artists.forEach(a => { artist_hrefs.add(a.href) });
                return [song.track.uri, '"'+song.track.name.replace(/"/g,'')+'"', '"'+song.track.album.name.replace(/"/g,'')+'"',
                    song.track.duration_ms, song.track.popularity, song.track.album.release_date,
                    '"'+song.track.artists.map(artist => { return artist.name }).join(',')+'"',
                    song.added_by.uri, song.added_at]
            });
        });
    });

    // Make queries on all the artists, because this json is where genre information lives. Unfortunately this
    // means a second wave of traffic.
    let genre_promise = data_promise.then(() => {
        let artists_promises = Array.from(artist_hrefs).map(href => utils.apiCall(href, access_token));
        return Promise.all(artists_promises).then(responses => {
          let artist_genres = {};
          responses.forEach(artist => { artist_genres[artist.name] = artist.genres.join(','); });
          return artist_genres;
        });
    });

    // join genres to the table, label the columns, and put all data in a single csv string
    return Promise.all([data_promise, genre_promise]).then(values => {
        [data, artist_genres] = values;

        data = data.flat();
        data.forEach(row => {
            artists = row[6].substring(1, row[6].length-1).split(','); // strip the quotes
            deduplicated_genres = new Set(artists.map(a => artist_genres[a]).join(",").split(",")); // join and split and take set
            row.push('"'+Array.from(deduplicated_genres).filter(x => x != "").join(",")+'"'); // remove empty strings
        });
        data.unshift(["Spotify URI", "Track Name", "Album Name", "Duration (ms)",
            "Popularity", "Release Date", "Artist Name(s)", "Added By", "Added At", "Genres"]);

        csv = '';
        data.forEach(row => { csv += row.join(",") + "\n" });
        return csv;
    });
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM