搜尋套件、儲存庫與 APP 分類

套件詳情v4.3.4

spotify_sdk

一個 Flutter 插件,讓您與 Spotify SDK 和驗證庫進行通訊

近 30 天下載
3100
喜歡數
162
Pub 分數
160

安裝套件

flutter pub add spotify_sdk

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

spotify_sdk 套件是一個 Flutter 插件,可實現與 Spotify SDK 和驗證程式庫的整合,讓開發者能在其 Flutter 應用中與 Spotify 的音樂服務進行互動。它支援使用者驗證、播放控制以及存取 Spotify 的豐富音樂資料。此套件專為與 Spotify API 實現無縫通訊而設計,簡化了在應用中嵌入音樂功能的過程。該套件支援 Android 與 iOS 平台,但可能需要進行平台特定的設定。由 tobibusch.dev 維護,並託管於 GitHub 上,以供社群貢獻。

適用情境

  • 整合 Spotify 登錄和驗證
  • 在應用內控制音樂播放
  • 顯示使用者的播放清單和歌曲
  • 建構音樂發現功能
  • 從應用中啟用歌曲分享
  • 在設備間同步播放狀態

主要特色

  • Spotify OAuth2 認證
  • 播放控制(播放/暫停/快進)
  • 訪問使用者個人檔案和播放清單
  • 支援軌道和專輯元數據
  • 即時播放狀態更新
  • 跨平台相容性

適合對象

  • 音樂串流應用
  • 播客播放器整合
  • 社交音樂分享功能
  • 個人化播放清單建構器
  • 開發者使用 Spotify 進行原型設計
  • 需要離線音樂同步的應用

使用建議

  • 需要 Spotify 開發者帳戶
  • 需要在 Spotify 電腦版儀表板中正確註冊應用程式
  • 平台特定的設定需要
  • 受限於 Spotify 的 API 範圍權限
  • 可能需要額外處理以實現背景播放
  • 依賴外部 Spotify SDK 才能實現完整功能

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

spotify_sdk

pub.dev build build


Description

This is a flutter package that wraps the native iOS and Android Spotify "remote" SDKs as well as the Spotify Web Playback SDK for web. Since it wraps the native SDKs it has the same features and limitations.

[!IMPORTANT] Upgrading to 4.0.0? Check out the 4.0.0 Migration Guide for important migration instructions regarding Android zero-configuration setup, Spotify Android Auth SDK v5.0.0 manifest registration, and typed SpotifyException domain error handling.

Setup

Android

This package uses both the Spotify App Remote SDK and the Spotify Authentication Library.

From the Spotify Android SDK Quick Start, you need to do the following:

  1. Register your app in the Spotify Developer Portal. Add your package name, a SHA-1 fingerprint of your signing certificate, and a Redirect URI in the app settings on the dashboard.
  2. Register the Redirect Activity: Inside the <application> tag of your android/app/src/main/AndroidManifest.xml file, declare the RedirectUriReceiverActivity (note the .browser. in the package path required by Spotify Auth SDK v5.0.0):
<activity
    android:name="com.spotify.sdk.android.auth.browser.RedirectUriReceiverActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data
            android:scheme="spotify-sdk"
            android:host="auth"/>
    </intent-filter>
</activity>

[!WARNING] You must use the exact class name com.spotify.sdk.android.auth.browser.RedirectUriReceiverActivity. The old manifestPlaceholders in app/build.gradle are no longer supported.

  1. No SDK Download Needed: The plugin automatically resolves, downloads, and configures the spotify-app-remote library AAR file during compilation. You do not need to manually download AAR files or edit your settings.gradle file.
iOS

Register your app in the spotify developer portal. You also need to register your Bundle ID as well as a Redirect URI.

Follow the instructions in the section Setup the iOS SDK of Spotify iOS SDK Quick Start.

Web
  1. Register your app in the spotify developer portal. You need to provide a redirect URL which points to a dedicated page on a website you own.

  2. Paste the following onto the webpage, which you linked to in your redirect URL.

<!DOCTYPE html>
<html>
  <head>
    <title>Authenticating Spotify</title>
  </head>
  <body>
	<p>Please wait while we authenticate Spotify...</p>
	<script type="text/javascript">
		if(window.opener) {
			window.opener.postMessage('?' + window.location.href.split('?')[1], "*");
		} else {
			window.close();
		}
	</script>
  </body>
</html>
  1. Optionally add this to your Flutter app web/index.html to avoid a Javascript TypeError: r.__extends is not a function error in development mode.
<script src="https://sdk.scdn.co/spotify-player.js"></script>
<script>
  window.onSpotifyWebPlaybackSDKReady = (evt) => {};
</script>

You need Spotify Premium to access the Web SDK.

Usage

To start using this package first import it in your Dart file.

import 'package:spotify_sdk/spotify_sdk.dart';

To connect to the Spotify app you can call connectToSpotifyRemote(...) or getAccessToken(...). In both of these methods you need the client id, which you will find in the Spotify developer dashboard and the redirect url you set there for that specific client.

await SpotifySdk.connectToSpotifyRemote(clientId: "", redirectUrl: "")

Subscribe to PlayerState or PlayerContext streams only after connecting successfully

SpotifySdk.subscribePlayerState();
SpotifySdk.subscribePlayerContext();

If you want to use the web api as well you have to use this method to get the access token. You can specify multiple scopes by separating them with a comma "," as shown below. For more information on scopes you can refer to Spotify Authorization Scopes Guide

final accessToken = await SpotifySdk.getAccessToken(clientId: "", redirectUrl: "", scope: "app-remote-control,user-modify-playback-state,playlist-read-private");

On Web you can use the token that you get from getAccessToken(...) and then pass it to connectToSpotifyRemote(...). This will avoid having to send user through two Spotify OAuth prompts. You should not persist this token, nor supply a different token, because the refresh token is only set interally by getAccessToken or connectToSpotifyRemote.

On iOS you can store the token that you get from getAccessToken(...) and then pass it to connectToSpotifyRemote(...) during the next session. This will avoid having to switch to the Spotify app for establishing the connection. This library does not handle storing the token. It is up to you to persist it wherever you see fit. Keep in mind that this feature is currently quite buggy in the native iOS SDK and has many side effects like random disconnections. Proceed with caution.

On iOS Spotify starts playing music when attempting connection. This is a default behavior and there is no official way to prevent this with the currently supported authentication flows. You have the option to pass a Spotify URI upon connection or set it to a blank string to play the last played song. There is an undocumented workaround if you don't want music to start playing which is to pass an invalid Spotify URI instead. This is not officially supported by the Spotify SDK or this library and it can fail or stop working at any time!

Have a look in the example for detailed insights on how you can use this package.

Token Swap & Utilities

If your application architecture uses an intermediate backend to exchange Spotify authorization codes and protect your Client Secret, you can retrieve the raw authorization code using getSwapToken(...):

final authorizationCode = await SpotifySdk.getSwapToken(
  clientId: "YOUR_CLIENT_ID",
  redirectUrl: "YOUR_REDIRECT_URL",
  scope: "app-remote-control,user-modify-playback-state",
);

You can also check if the native Spotify application is installed on the user's device:

final isInstalled = await SpotifySdk.isSpotifyInstalled();
Error Handling

The SDK provides strongly-typed domain exceptions extending SpotifyException:

try {
  await SpotifySdk.connectToSpotifyRemote(
    clientId: 'YOUR_CLIENT_ID',
    redirectUrl: 'YOUR_REDIRECT_URL',
  );
} on SpotifyNotInstalledException catch (e) {
  // Prompt user to install Spotify
} on SpotifyAuthenticationException catch (e) {
  // Handle auth failure or user cancellation
} on SpotifyConnectionException catch (e) {
  // Handle remote connection errors
} on SpotifyPlaybackException catch (e) {
  // Handle playback or track seek errors
} on SpotifyException catch (e) {
  // Handle any general Spotify error (e.message, e.code, e.cause)
}
Api
Connecting/Authenticating
Function Description Android iOS Web
connectToSpotifyRemote Connects the App to Spotify ✔ ✔ ✔
getAccessToken Gets the Access Token that you can use to work with the Web Api ✔ ✔ ✔
getSwapToken Gets an OAuth Authorization Code for custom token swap backend servers ✔ ✔ ✔
isSpotifyInstalled Checks if the Spotify application is installed on the device ✔ ✔ ✔
disconnect Disconnects the app connection ✔ ✔ ✔
subscribeConnectionStatus Subscribes to the current connection status. ✔ ✔ ✔
Player Api

The playerApi as described here.

Function Description Android iOS Web
getCrossFadeState Gets the current crossfade state ✔ ✔ ✔
getPlayerState Gets the current player state ✔ ✔ ✔
pause Pauses the current track ✔ ✔ ✔
play Plays the given spotifyUri ✔ ✔ ✔
queue Queues given spotifyUri ✔ ✔ ✔
resume Resumes the current track ✔ ✔ ✔
seekTo Seeks the current track to the given position in milliseconds ✔ ✔ ✔
seekToRelativePosition Adds to the current position of the track the given milliseconds ✔ ✔ ✔
setPodcastPlaybackSpeed Set playback speed for Podcast ✔ ❌ ❌
setRepeatMode Set the repeat mode ✔ ✔ ✔
setShuffle Set the shuffle mode ✔ ✔ ✔
skipNext Skips to next track ✔ ✔ ✔
skipPrevious Skips to previous track ✔ ✔ ✔
skipToIndex Skips to track at specified index in album or playlist ✔ ✔ ✔
subscribePlayerContext Subscribes to the current player context ✔ ✔ ✔
subscribePlayerState Subscribes to the current player state ✔ ✔ ✔
toggleRepeat Cycles through the repeat modes ✔ ✔ ✔
toggleShuffle Cycles through the shuffle modes ✔ ✔ ✔

On Web, an automatic call to play may not work due to media activation policies which send an error: "Authentication Error: Browser prevented autoplay due to lack of interaction". This error is ignored by the SDK so you can still present a button for the user to click to play or resume to start playback. See the Web SDK Troubleshooting guide for more details.

Images Api

The imagesApi as described here.

Function Description Android iOS Web
getImage Get the image from the given spotifyUri ✔ ✔ ✔
User Api

The userApi as described here.

Function Description Android iOS Web
addToLibrary Adds the given spotifyUri to the users library ✔ ✔ ✔
getCapabilities Gets the current users capabilities ✔ ✔ ✔
getLibraryState Gets the current library state ✔ ✔ ✔
removeFromLibrary Removes the given spotifyUri to the users library ✔ ✔ ✔
subscribeCapabilities Subscribes to the current users capabilities ✔ ✔ ✔
subscribeUserStatus Subscribes to the current users status ✔ ✔ ✔
Connect Api

The connectApi as described here.

Function Description Android iOS Web
switchToLocalDevice Switch to play music on this (local) device ✔ ❌ ✔

Migration

spotify-auth: moving from locally sourced aar to maven central

spotify-auth SDK is now retrieved via Maven Central instead of being sourced from an AAR file

  • Steps to remove the locally sourced spotify-auth SDK:
    • android/settings.gradle -> remove ':spotify-auth'
    • android/spotify-auth/build.gradle -> remove file
    • android/spotify-auth/spotify-auth-release-x.x.x.aar -> remove file

Official Spotify Docs

所屬分類

依賴

依賴清單 4 項

  • spotify_sdk_android^4.3.4
  • spotify_sdk_ios^4.3.4
  • spotify_sdk_platform_interface^4.3.4
  • spotify_sdk_web^4.3.4

原始碼儲存庫

使用此套件的專案