使用Spotify Web Playback SDK和React

问题描述 投票:4回答:1

Spotify在测试版中有一项新功能,支持在浏览器,Web Playback SDK中完整播放歌曲。该文档显示了使用主HTML文件中的脚本标记立即初始化播放器的示例。这需要在脚本中立即设置访问令牌。我的问题是我正在创建一个React应用程序,我只想在用户单击按钮登录其Spotify帐户时初始化播放器。为了在此事件发生时仅加载脚本,我使用的是react-load-script。我想要的流程是:用户点击按钮登录他们的Spotify帐户,一旦他们的登录通过Spotify认证我的应用程序收到访问令牌,然后加载Web回放脚本,一旦加载脚本,就会调用回调函数并使用访问令牌初始化播放器。

问题是Spotify对象在加载spotify-player脚本之前不存在。当实际调用handleScriptLoad回调时,定义了Spotify对象,但是在编译代码时,它不是。有没有人有任何想法如何解决这个问题?

来自相关React组件的代码示例:

import Script from 'react-load-script'

...

handleScriptLoad = () => {
const token = this.props.tokens.access
const player = new Spotify.Player({      // Spotify is not defined until 
  name: 'Spotify Web Player',            // the script is loaded in 
  getOAuthToken: cb => { cb(token) }
})

player.connect()
}

...

在我的React组件的render方法中:

<Script 
  url="https://sdk.scdn.co/spotify-player.js" 
  onError={this.handleScriptError} 
  onLoad={this.handleScriptLoad}
/>
javascript reactjs spotify dynamic-script-loading
1个回答
2
投票

从理论上讲,这是可能的。

Web Playback SDK将通过外部脚本异步加载SDK中的window.Spotify对象。因此,等待定义对象应该可以解决问题:

handleScriptLoad = () => {
  return new Promise(resolve => {
    if (window.Spotify) {
      resolve();
    } else {
      window.onSpotifyWebPlaybackSDKReady = resolve;
    }
  });
}

那应该可以解决你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.