tl;dr:工作片段在这个答案的底部!
你做这个
play({
playerInstance: new Spotify.Player({ name: "..." }),
spotify_uri: 'spotify:track:7xGfFoTpQ2E7fRF5lN10tr',
});
以下之外。
window.onSpotifyWebPlaybackSDKReady = () => {
// You can now initialize Spotify.Player and use the SDK
};
意思是play
立即被调用,无需等待 Spotify Web Playback SDK 加载。正如评论所说Spotify.Player
可以尽快使用onSpotifyWebPlaybackSDKReady
被称为。
另一个问题是您实际上从未创建过 Spotify Connect 设备。这是使用 Spotify Web API 控制该设备所必需的。这可以通过调用来实现connect
on the Spotify.Player
实例。为了知道什么时候connect
完成后,播放器已准备好播放歌曲,您需要首先定义侦听器,如下所示。
player.addListener('ready', ({ device_id }) => {
console.log('Ready with Device ID', device_id);
});
因此,您实际上需要两个不同的 Spotify API 才能实现您的目标。首先,您需要 Spotify Web Playback SDK 才能创建 Spotify Connect 设备(Spotify 文档将其称为播放器)。之后,您可以使用 Spotify 的 Web API 控制这个确切的 Spotify Connect 设备。
以下片段将播放该歌曲。
警告:这将在您的浏览器中播放音乐,无需任何控制元素!
此代码片段需要一个可以获取的访问令牌here https://developer.spotify.com/documentation/web-playback-sdk/quick-start/点击绿色按钮说Get Your Web Playback SDK Access Token
。然后需要将令牌复制粘贴到代码片段的第 11 行中,替换<YOUR_ACCESS_TOKEN_HERE>
.
索引.html
<!-- Load the Spotify Web Playback SDK -->
<script src="https://sdk.scdn.co/spotify-player.js"></script>
<script>
// Called when the Spotify Web Playback SDK is ready to use
window.onSpotifyWebPlaybackSDKReady = () => {
// Define the Spotify Connect device, getOAuthToken has an actual token
// hardcoded for the sake of simplicity
var player = new Spotify.Player({
name: 'A Spotify Web SDK Player',
getOAuthToken: callback => {
callback('<YOUR_ACCESS_TOKEN_HERE>');
},
volume: 0.1
});
// Called when connected to the player created beforehand successfully
player.addListener('ready', ({ device_id }) => {
console.log('Ready with Device ID', device_id);
const play = ({
spotify_uri,
playerInstance: {
_options: {
getOAuthToken,
id
}
}
}) => {
getOAuthToken(access_token => {
fetch(`https://api.spotify.com/v1/me/player/play?device_id=${id}`, {
method: 'PUT',
body: JSON.stringify({ uris: [spotify_uri] }),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
},
});
});
};
play({
playerInstance: player,
spotify_uri: 'spotify:track:7xGfFoTpQ2E7fRF5lN10tr',
});
});
// Connect to the player created beforehand, this is equivalent to
// creating a new device which will be visible for Spotify Connect
player.connect();
};
</script>