简体   繁体   English

Spotify Web播放SDK

[英]Spotify Web Playback SDK

Hey im following this example from Glitch https://glitch.com/~spotify-web-playback 嗨,我是按照Glitch https://glitch.com/~spotify-web-playback中的示例进行操作的

When i run the example they give on their Glitch site the app runs perfectly. 当我运行示例时,他们在自己的Glitch网站上提供了该应用程序的完美运行。 However once i build the app and run it using node (off the localhost) i never reach the Spotify Login page. 但是,一旦我构建了应用程序并使用节点(在本地主机上)运行它,就再也无法访问Spotify登录页面。 Just wondering if anyone has the same problems when they try to build the app and where i could be going wrong. 只是想知道是否有人在尝试构建应用程序时遇到相同的问题,而我可能会出错。 I do not change any of the code other than including my own 'ClientId'. 除了包含我自己的“ ClientId”外,我不会更改任何代码。 The only difference is instead of using index.html i use an index.ejs file as i am calling it from my following server.js file: 唯一的区别是,我使用index.ejs文件而不是使用index.html,因为我是从下面的server.js文件中调用它的:

const express = require('express');
const bodyParser = require('body-parser');
const app = express()

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs')

app.get('/', function (req, res) {
  res.render('index', {userInput: null, error: null});
})

app.post('/', function (req, res) {
    res.render('index');
  })

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

index.ejs index.ejs

<!DOCTYPE html>
<html>

  <head>
    <title>Spotify Web Playback SDK Template</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://sp-bootstrap.global.ssl.fastly.net/8.0.0/sp-bootstrap.min.css" rel="stylesheet" />
    <script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous"></script>

    <!-- Include the Web Playback SDK -->
    <script src="https://sdk.scdn.co/spotify-player.js"></script>

    <!-- Include our Javascript -->
    <script src="/script.js" defer></script>
  </head>

  <body class="container">
    <h1 class="text-salmon">Spotify Web Playback SDK Template</h1>
    <h4>This app uses the implicit grant authorization flow to get an access token and initialise the Web Playback SDK. It then uses the Spotify Connect Web API to play a song.</h4>
    <p>If everything is set up properly, you should hear some music!</p>
    <img id="current-track"/>
    <h3 id="current-track-name"></h3>
    <a class="btn btn-salmon btn-lg" href="https://glitch.com/edit/#!/spotify-web-playback">Get started!</a>
  </body>

</html>

script.js 的script.js

// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
  if (item) {
    var parts = item.split('=');
    initial[parts[0]] = decodeURIComponent(parts[1]);
  }
  return initial;
}, {});
window.location.hash = '';

// Set token
let _token = hash.access_token;
//console.log("Made it here");
const authEndpoint = 'https://accounts.spotify.com/authorize';

// Replace with your app's client ID, redirect URI and desired scopes
const clientId = 'CLIENTID';
const redirectUri = 'https://spotify-web-playback.glitch.me';
const scopes = [
  'streaming',
  'user-read-birthdate',
  'user-read-private',
  'user-modify-playback-state'
];

// If there is no token, redirect to Spotify authorization
if (!_token) {
  window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token&show_dialog=true`;
}

// Set up the Web Playback SDK

window.onSpotifyPlayerAPIReady = () => {
  const player = new Spotify.Player({
    name: 'Web Playback SDK Template',
    getOAuthToken: cb => { cb(_token); }
  });

  // Error handling
  player.on('initialization_error', e => console.error(e));
  player.on('authentication_error', e => console.error(e));
  player.on('account_error', e => console.error(e));
  player.on('playback_error', e => console.error(e));

  // Playback status updates
  player.on('player_state_changed', state => {
    console.log(state)
    $('#current-track').attr('src', state.track_window.current_track.album.images[0].url);
    $('#current-track-name').text(state.track_window.current_track.name);
  });

  // Ready
  player.on('ready', data => {
    console.log('Ready with Device ID', data.device_id);

    // Play a track using our new device ID
    play(data.device_id);
  });

  // Connect to the player!
  player.connect();
}

// Play a specified track on the Web Playback SDK's device ID
function play(device_id) {
  $.ajax({
   url: "https://api.spotify.com/v1/me/player/play?device_id=" + device_id,
   type: "PUT",
   data: '{"uris": ["spotify:track:5ya2gsaIhTkAuWYEMB0nw5"]}',
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
   success: function(data) { 
     console.log(data)
   }
  });
}

I'm pretty sure I'm way too late to help you with this, but maybe some unfortunate soul in the future still needs an answer... 我很确定我为时已晚,无法为您提供帮助,但也许将来某些不幸的人仍然需要答案...

  1. You have to change the redirectUri to your own website path in the script.js file (line 21). 您必须在script.js文件(第21行)中将redirectUri更改为您自己的网站路径。

Then you have to go to your Spotify Developer Dashboard to add that link to your app. 然后,您必须转到Spotify开发人员仪表板以将该链接添加到您的应用程序。

  1. Go to this link: https://developer.spotify.com/dashboard/applications 转到此链接: https : //developer.spotify.com/dashboard/applications
  2. Select your application -> Edit Settings -> Redirect Uri's 选择您的应用程序->编辑设置->重定向Uri
  3. Add that same link there 在此处添加相同的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM