首页 > 解决方案 > 通过 spotify web api 和 javascript 播放歌曲的问题

问题描述

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

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

然后我开始查看位于此处的 Web Playback 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>

标签: javascriptspotify

解决方案


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来工作。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 设备。


以下片段将播放这首歌。

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

该片段需要一个访问令牌,可以通过单击绿色按钮在此处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>

推荐阅读