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

时间:2018-10-18 18:23:52

标签: javascript spotify

我正在构建一个与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>

1 个答案:

答案 0 :(得分:1)

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播放SDK才能创建Spotify Connect设备(Spotify文档将其称为播放器)。之后,您可以使用Spotify的Web API控制此确切的Spotify Connect设备。


以下片段将播放歌曲。

警告:这将在您的浏览器中播放音乐而没有任何控件!

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

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>
相关问题