A react native module for the Spotify SDK
NOTE: This repo is using the deprecated Spotify streaming SDKs. I have been told by users that it is now no longer functional, since Spotify has turned off the API.
react-native-spotify-remote is being worked on by cjam to use the newer "remote" SDK.
To add the Spotify SDK to your project, cd into your project directory and run the following commands:
npm install --save rn-spotify-sdk
react-native link react-native-events
react-native link rn-spotify-sdk
Next, do the manual setup for each platform:
Manually add SpotifyMetadata.framework
and SpotifyAudioPlayback.framework
from node_modules/rn-spotify-sdk/ios/external/SpotifySDK
to Linked Frameworks and Libraries in your project settings. Then add ../node_modules/rn-spotify-sdk/ios/external/SpotifySDK
to Framework Search Paths in your project settings.
Edit android/build.gradle
and add flatDir
...
allprojects {
repositories {
mavenLocal()
jcenter()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
flatDir {
dirs project(':rn-spotify-sdk').file('libs'), 'libs'
}
}
}
...
Edit android/app/build.gradle
and add packagingOptions
...
buildTypes {
release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
packagingOptions {
pickFirst 'lib/armeabi-v7a/libgnustl_shared.so'
pickFirst 'lib/x86/libgnustl_shared.so'
exclude 'lib/arm64-v8a/libgnustl_shared.so'
exclude 'lib/x86_64/libgnustl_shared.so'
}
...
In some cases, the two exclude
lines cause issues when compiling and can be omitted. I need to look further into what causes this.
On Android, react-native link
has a bug where it imports RNSpotifyPackage
using the wrong bundle. You may have to make the following change to MainApplication.java
:
...
import com.spotify.sdk.android.authentication.RNSpotifyPackage; // remove this line
import com.lufinkey.react.spotify.RNSpotifyPackage; // replace with this line
...
If you have issues linking the module, please check that gradle is updated to the latest version and that your project is synced. Please reference the example app to ensure you've implemented things correctly before opening any issues.
import Spotify from 'rn-spotify-sdk';
Session
Contains information about a session
Properties
PlaybackState
Contains information about the current state of the player
Properties
PlaybackTrack
Contains information about a track in the playback queue
Properties
PlaybackMetadata
Contains information about the previous, current, and next tracks in the player
Properties
PlaybackEvent
Contains information about a playback event and the state of the player.
Properties
This module uses react-native-events, so it has all of the same methods as an EventEmitter object. All of the events except for 'disconnect' / 'reconnect' (on Android) and 'login' / 'logout' come from Spotify's native SDK and are simply forwarded to javascript. If one of these events occurs at a weird time or has strange data, please open an issue on Spotify's ios-streaming-sdk or android-streaming-sdk repo, and not here.
'login'
session
{Session}Emitted when the module has successfully logged in.
'logout'
Emitted when the module is logged out.
'sessionRenewed'
session
{Session}Emitted when the session has been renewed.
'play'
event
{PlaybackEvent}Emitted when playback has started or has resumed.
'pause'
event
{PlaybackEvent}Emitted when playback is paused.
'trackChange'
event
{PlaybackEvent}Emitted when playback of a new/different track starts.
'metadataChange'
event
{PlaybackEvent}Emitted when metadata has changed. This event occurs when playback starts or changes to a different context, when a track switch occurs, etc. This is an informational event that does not require action, but should be used to keep the UI display updated with the latest metadata information.
'contextChange'
event
{PlaybackEvent}Emitted when playback starts or changes to a different context than was playing before, such as a change in album or playlist.
'shuffleStatusChange'
event
{PlaybackEvent}Emitted when "shuffle" is switched on or off.
'repeatStatusChange'
event
{PlaybackEvent}Emitted when "repeat" is switched on or off.
'active'
event
{PlaybackEvent}Emitted when this device has become the active playback device. This event occurs when the users moves playback to this device using Spotify Connect.
'inactive'
event
{PlaybackEvent}Emitted when this device is no longer the active playback device. This event occurs when the user moves playback to a different device using Spotify Connect.
'permissionLost'
event
{PlaybackEvent}Emitted when this device has temporarily lost permission to stream audio from Spotify. A user can only stream audio on one of her devices at any given time. If playback is started on a different device, this event may occur.
'audioFlush'
event
{PlaybackEvent}Emitted when the application should flush its audio buffers (you don't need to deal with this since that's handled by the native code). For example, this event occurs when seeking to a different position within a track.
'audioDeliveryDone'
event
{PlaybackEvent}Emitted when the library reaches the end of a playback context and has no more audio to deliver.
'trackDelivered'
event
{PlaybackEvent}Emitted when the application accepted all samples from the current track. This is an informative event that indicates that all samples from the current track have been delivered to and accepted by the application. The track has not yet finished playing the last audio sample, but no more audio will be delivered for this track. For nearly all intents and purposes, the track has finished playing.
'disconnect'
Emitted when the player loses network connectivity.
'reconnect'
Emitted when the player regains network connectivity.
'temporaryPlayerError'
Emitted when service has been interrupted, usually by lack of network access. However, it can also occur if there is a problem with Spotify's backend services, or also when the user switches from WiFi to 3G. These errors can occur in many non-critical situations, and thus it is not necessary to show toasts or alert dialogs when receiving this event, or else you will unnecessarily annoy or panic the user. However, it can be useful to know about these events if operations are consistently failing, in which case showing a toast or alert may be justified.
'playerMessage'
message
{String}Called when the player has recieved a message for the end user from the Spotify service.
initialize( options )
Initializes the Spotify module and resumes a logged in session if there is one. This must be the first method you call when using this module.
Parameters
300
'AVAudioSessionCategoryPlayback'
Returns
isInitialized()
Checks if the Spotify module has been initialized yet.
Returns
isInitializedAsync()
Checks if the Spotify module has been initialized yet, but returns a Promise that resolves to the result.
Returns
login( options? )
Opens a UI to log into Spotify.
Parameters
Returns
isLoggedIn()
Checks if the client is logged in.
Returns
isLoggedInAsync()
Checks if the client is logged in, but returns a Promise that resolves to the result.
Returns
logout()
Logs out of Spotify.
Returns
getSession()
Gives information about the current session.
Returns
getSessionAsync()
Gives information about the current session, but returns a Promise that resolves to the result.
Returns
renewSession()
Renews a logged in session. If no token refresh URL was given to initialize or if the session does not have a refresh token, this function returns without error
Returns
authenticate( options? )
Opens a UI to perform the auth flow for Spotify, but returns a session instead of logging in.
Parameters
Returns
loginWithSession( options )
Logs into the app with a given session
Parameters
Returns
playURI( spotifyURI, startIndex, startPosition )
Play a Spotify URI.
Parameters
Returns
queueURI( spotifyURI )
Queue a Spotify URI. WARNING: This function has proven to be very inconsistent and buggy.
Parameters
Returns
setPlaying( playing )
Set the “playing” status of the player.
Parameters
Returns
getPlaybackState()
Gives the player's current state.
Returns
getPlaybackStateAsync()
Gives the player's current state, but returns a Promise that resolves to the result.
Returns
getPlaybackMetadata()
Gives information about the previous, current, and next track in the player.
Returns
getPlaybackMetadataAsync()
Gives information about the previous, current, and next track in the player, but returns a Promise that resolves to the result.
Returns
skipToNext()
Skips to the next track.
Returns
skipToPrevious()
Skips to the previous track.
Returns
seek( position )
Seeks to a position within the current track
Parameters
Returns
setShuffling( shuffling )
Enables or disables shuffling on the player.
Parameters
Returns
setRepeating( repeating )
Enables or disables repeating on the player.
Parameters
Returns
sendRequest( endpoint, method, params, isJSONBody )
Sends a general request to the spotify api. A list of potential endpoints can be found here.
Parameters
'v1/browse/new-releases'
Returns
getMe()
Retrieves information about the logged in Spotify user.
Returns
search( query, types, options? )
Sends a search request to spotify.
Parameters
'album'
, 'artist'
, 'playlist'
, and 'track'
.Returns
getAlbum( albumID, options? )
Gets Spotify catalog information for a single album.
Parameters
Returns
getAlbums( albumIDs, options? )
Gets Spotify catalog information for multiple albums identified by their Spotify IDs.
Parameters
Returns
getAlbumTracks( albumID, options? )
Gets Spotify catalog information about an album’s tracks.
Parameters
Returns
getArtist( artistID, options? )
Gets Spotify catalog information for a single artist.
Parameters
Returns
getArtists( artistIDs, options? )
Gets Spotify catalog information for several artists based on their Spotify IDs.
Parameters
Returns
getArtistAlbums( artistID, options? )
Gets Spotify catalog information about an artist’s albums.
Parameters
Returns
getArtistTopTracks( artistID, country, options? )
Gets Spotify catalog information about an artist’s top tracks by country.
Parameters
Returns
getArtistRelatedArtists( artistID, options? )
Gets Spotify catalog information about artists similar to a given artist.
Parameters
Returns
getTrack( trackID, options? )
Gets Spotify catalog information for a single track identified by its unique Spotify ID.
Parameters
Returns
getTracks( trackIDs, options? )
Gets Spotify catalog information for multiple tracks based on their Spotify IDs.
Parameters
Returns
getTrackAudioAnalysis( trackID, options? )
Gets a detailed audio analysis for a single track identified by its unique Spotify ID.
Parameters
Returns
getTrackAudioFeatures( trackID, options? )
Gets audio feature information for a single track identified by its unique Spotify ID.
Parameters
Returns
getTracksAudioFeatures( trackIDs, options? )
Gets audio features for multiple tracks based on their Spotify IDs.
Parameters
Returns
In order for your app to stay logged into Spotify for more than an hour, you must set up your own server with endpoints for token swap and refresh, and specify your tokenSwapURL
and tokenRefreshURL
parameters in the Spotify.initialize
method
The tokenSwapURL
parameter is used to swap the authentication code provided by the Spotify login process for an access token and a refresh token.
The tokenRefreshURL
parameter is used to retrieve new access tokens for the user using the refresh token received from the tokenSwapURL
.
Both URLs are queried using POST with a Content-Type of application/x-www-form-urlencoded
.
You can find an example server implementation here.
Refresh tokens are part of OAuth standard. If you are not familiar with them, Understanding Refresh Tokens can give you a basic idea on how they work.
This module only works for Spotify Premium users.