通过Spotify Web API和Java脚本播放歌曲时出现问题 [英] problem playing songs via the spotify web api and javascript

查看:25
本文介绍了通过Spotify Web API和Java脚本播放歌曲时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然后我开始查看位于以下位置的Web播放API:

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

我打算用C#编写它的大部分内容,因为我的C#比我的Java脚本强大得多。C#片段正在运行。我可以得到授权令牌,调出我的播放列表和曲目。我打算将此信息传递给Java脚本。

我从Spotify开发人员页面中提取了以下脚本。我只是有点理解它,所以我不知道为什么它不工作。我们非常感谢您能提供的任何帮助。

<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播放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获得访问令牌。然后需要将令牌复制粘贴到替换<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>

这篇关于通过Spotify Web API和Java脚本播放歌曲时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆