我在本地站点上使用 Spotify Playback SDK。这是我的代码:
window.onSpotifyWebPlaybackSDKReady = () => {
const token = "<?php echo $_SESSION["accessToken"] ?>";
const player = new Spotify.Player({
name: 'Spotify Clone',
getOAuthToken: cb => {
cb(token);
}
});
window.player = player;
// Connect to the player!
window.player.connect();
// Error handling
window.player.addListener('initialization_error', ({message}) => {
console.error(message);
});
window.player.addListener('authentication_error', ({message}) => {
console.error(message);
});
window.player.addListener('account_error', ({message}) => {
console.error(message);
});
window.player.addListener('playback_error', ({message}) => {
console.error(message);
});
// Playback status updates
window.player.addListener('player_state_changed', state => {
console.log(state);
});
// Ready
window.player.addListener('ready', ({device_id}) => {
console.log('Ready with Device ID', device_id);
});
// Not Ready
window.player.addListener('not_ready', ({device_id}) => {
console.log('Device ID has gone offline', device_id);
});
}
document.getElementById("play-arrow").onclick = function () {
window.player.togglePlay().then(() => {
console.log('Toggled playback!');
});
}
其他一切都正常。例如我可以在浏览器中显示当前位置。像togglePlay、skip或seek之类的所有功能仅在连接到设备的10%时间内起作用,我必须多次重新加载页面并连接。这是我得到的错误:
index.js:9 Uncaught TypeError: Cannot read property 'togglePlay' of null
at h._playbackControl (index.js:9)
at h._onTogglePlay (index.js:9)
at h._handleMessages (index.js:9)
at r._receiveMessage (index.js:9)
window.player 不为 Null,我在控制台检查过。
有什么想法吗?
我刚刚在 next.js 项目中使用 Spotify Webplayback SDK 时遇到了同样的问题。
对我来说,问题在于我的 next.config.js 中有
reactStrictMode: true
。
如果您使用的是 React strict 模式,请尝试禁用它。