通过 Spotify 网络 api 和 javascript 播放歌曲时出现问题

problem playing songs via the spotify web api and javascript

我正在构建一个与 spotify 交互的基于 Web 的应用程序。我从 C# 开始,访问 API 没有问题,拉出我的播放列表并从中拉出曲目,但似乎无法使用位于此处的 spotify Web API 播放歌曲:

https://developer.spotify.com/documentation/web-api/

然后我开始查看位于此处的网络播放 API:

https://developer.spotify.com/documentation/web-playback-sdk/

我打算用c#写大部分,因为我的c#比我的javascript强多了。 c# 部分正在工作。我可以获得授权令牌,提取我的播放列表和曲目。我打算将此信息传递给 javascript.

我从 Spotify 开发者页面中提取了以下 javascript。我只是有点理解它,所以我不知道为什么它不起作用。非常感谢您提供的任何帮助。

<script src="https://sdk.scdn.co/spotify-player.js"></script>

<script>

window.onSpotifyWebPlaybackSDKReady = () => {
  // You can now initialize Spotify.Player and use the SDK
};

const play = ({
  spotify_uri,
  playerInstance: {
    _options: {
      getOAuthToken,
      id
    }
  }
}) => {
  getOAuthToken(access_token => {
    fetch('https://api.spotify.com/v1/me/player/play', {
      method: 'PUT',
      body: JSON.stringify({ uris: [spotify_uri] }),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ${myaccesstoken}'
      },
    });
  });
};

play({
  playerInstance: new Spotify.Player({ name: "..." }),
  spotify_uri: 'spotify:track:7xGfFoTpQ2E7fRF5lN10tr',
});

</script>

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 来控制确切设备所必需的。这通过在 Spotify.Player 实例上调用 connect 来实现。为了知道 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 设备

以下代码段将播放歌曲。

警告:这将在您的浏览器中播放音乐而无需任何控制元素!

此代码段需要一个访问令牌,可以通过单击绿色按钮 Get Your Web Playback SDK Access Token 获得 here。然后需要将令牌复制粘贴到替换 <YOUR_ACCESS_TOKEN_HERE>.

代码段的第 11 行

index.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>