iT邦幫忙

1

工作散記 - 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 在專案中的可行性。

後續這裡有新坑再來更新~


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言