我想知道是否有办法知道哪个播放列表当前在spotify上播放。我已阅读API并找到了一个" isLoaded" function,返回一个布尔值。我可以浏览所有播放列表并获取哪一个是加载的,但我想知道是否有办法更直接地执行此操作。
答案 0 :(得分:2)
您可以使用以下命令找出播放器播放内容的uri
:
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
});
});
您可以使用uri
来获取属性,例如name
。在以下示例中,如果当前曲目的上下文是播放列表,我们将检索播放列表的名称:
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'
});
}
});
});