工作散记 - Spotify for Developers

jpg

embed

  • 连结格式:
    1. Podcast - https://open.spotify.com/embed-podcast/episode/<podcast ID>
    2. Song - https://open.spotify.com/embed/track/<song ID>
  • 取得内嵌程序码:
    1. 打开桌面版spotify
    2. 开启特定曲目或节目
    3. 点...图示 > 分享 > 复制多个内嵌程序码

长像这样

Imgur

以API取得资讯

到 Spotify for Developers 注册应用程序

  1. https://developer.spotify.com/dashboard/applications 新增应用程序
  2. 输入应用名称、描述後点选 create
  3. 建立後点选 EDIT SETTINGS
  4. 新增 Redirect URIs ,验证结束後的重导向的连结需要完全一致,spotify会在这个重导向连结後面加上hash param,其中包含重要的 access_token
  5. 复制 client ID,待会会用到

Authorization

Spotify的验证流程总共有四种。如果是纯Web前端的话,使用 Implicit Grant(Temporary user authorization)

png

官方有提供其中三种的验证范例程序: https://github.com/spotify/web-api-auth-examples

简单来说,这个流程可以在Web前端执行,只要有刚刚复制的client ID,就可以取得token,并透过token取得资讯。

不过要注意的是,token的有效时间是3600秒(1小时)。

除了 client ID 以外,还需要以下参数传递 -

程序演示

导向验证页面

const scopes = `streaming user-read-playback-position user-modify-playback-state user-read-playback-state user-read-private user-read-email`;
const redirectUri = `${API_HOST}/podcast/just_req=1`;
const authEndpoint = 'https://accounts.spotify.com/authorize';

const authURL = `${authEndpoint}?client_id=${encodeURIComponent(CFG_SPOTIFY_CLIENT_ID)}&scope=${encodeURIComponent(scopes)}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=token&state=123`;

window.location.href = authURL;

验证成功後,解析连结取得token

interface I_RedirectParams {
    access_token?: string;
    token_type?: string;
    expires_in?: number;
    state?: string;
}

function getRedirectParams():I_RedirectParams {
    var hashParams = {};
    var e, r = /([^&;=]+)=?([^&;]*)/g,
        q = window.location.hash.substring(1);
    while ( e = r.exec(q)) {
        hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
}

const params = getRedirectParams();
if (params?.access_token) {
  // do something ...
}

spotify-web-api-js

npm: https://www.npmjs.com/package/spotify-web-api-js

安装後,就可以直接以module的方式汇入,并将 spotify web api 用js wrap起来,提供一个方便的介面给开发者使用。另外他有type档,ts开发者也可开心用。

import SpotifyWebApi from 'spotify-web-api-js';

const spotifyApi = new SpotifyWebApi();

// 拿到token先给spotifyApi
spotifyApi.setAccessToken(params.access_token);

// e.g. 取得podcast节目资讯
const showID = '21ww46sryVYYw8zKr7afqX';
spotifyApi.getShow(showID).then(data => console.log(data));  

如果要了解 spotify web api 本身的内容 可到 https://developer.spotify.com/documentation/web-api/

Web Playback SDK

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

spotify web api 在音讯的部分,只提供30秒的音档连结。所以要取得完整的音源,要以 streaming 的方式取得,所以需要 Web Playback SDK 来做到这件事情。

首先先引入 SDK 的 script

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

新增player相关的event handler

ready事件取得device id,并往 https://api.spotify.com/v1/me/player/play 发 ajax


const play = (deviceID, token) => {
  const playaURL = `https://api.spotify.com/v1/me/player/play?device_id=${data.device_id}`;
  const d = { uris: ['spotify:track:5ya2gsaIhTkAuWYEMB0nw5'] };
  fetch(playaURL, {
    method: 'PUT',
    body: JSON.stringify(d),
    headers: new Headers({
        Authorization: `Bearer ${token}`,
    }),
  })
    .then((res) => res.json())
    .catch((error) => console.error('Error:', error))
    .then((response) => console.log('Success:', response));
}

if (_token) {
    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);
        });

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

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

注意事项

  • Web Playback SDK 是以 EME(Encrypted Media Extensions) 实作。应用页面须为 secure context。简单来说就是要 https 开头。如果是以 webpack dev server建立开发环境,设定 https:true 即可。
  • scope 一定要有 streaming user-read-private user-read-email 这三项
  • Web Playback SDK 需要 premium 会员才能使用

小记

後来因为需要 premium 才能往下一步前进,加上使用者会有 spotify 帐号的普及率不知道多高,主管就指示先pending 啦~

接下来有时间应该会先从比较普及的youtube开始着手,然後研究 react-player 在专案中的可行性。

後续这里有新坑再来更新~


<<:  [C]makefile范例实作,整理已有的程序码

>>:  [鼠年全马] W33 - Vue出一个旅馆预约平台(7)

30天程序语言研究

今天是30天程序语言研究的第十九天,由於深度学习老师多让我们上了python的进阶课程里面包括之前没...

Day27 海鲜义大利炖饭Risotto

在地狱厨房中,常常看到有人因为Risotto翻车导致戈登大吼骂人的画面,决定来挑战看看传统义大利炖...

[寿星优惠-2] 肉肉先生 Mr.zozo #当月寿星6折

9盎司沙朗牛,原价338+10%,寿星价NTD.237元(已包括服务费) 肉肉先生跟昨天的响厚牛排各...

第一天:为什麽 CI/CD 对软件开发来说是重要的?

日渐复杂的开发流程 还记得笔者第一个接触的程序语言是 PHP,其直译的设计、简单不复杂的语法,任何人...

Day 30 -- Rails 实作 Action Cable 即时交易功能

Action Cable 毫无疑问地在 Rails的发展史上立下了ㄧ个重要的里程碑,它将 WebSo...