1.6.1 • Published 8 years ago

nativescript-spotify v1.6.1

Weekly downloads
5
License
MIT
Repository
github
Last release
8 years ago

alt text

A NativeScript plugin for the Spotify iOS and Android SDKs.

Install

npm install nativescript-spotify --save

Prerequisites

Background

Usage

Platform Prerequisites

iOS

Setup

  • app.ts

Configure application launch phases to setup your Spotify App CLIENT_ID and REDIRECT_URL (the ones you created above in the developer account):

import * as application from 'application';
import {NSSpotifyConstants, NSSpotifyAuth} from 'nativescript-spotify';

class MyDelegate extends UIResponder {
  public static ObjCProtocols = [UIApplicationDelegate];
  
  public applicationDidFinishLaunchingWithOptions(application: UIApplication, launchOptions: NSDictionary): boolean {
    
    NSSpotifyConstants.CLIENT_ID = 'your spotify premium account api key';
    TNSSpotifyAuth.REDIRECT_URL = 'your-app-custom-url-scheme://spotifylogin';
    return true;
  }
}
application.ios.delegate = MyDelegate;
application.mainModule = "main-page";
application.cssFile = "./app.css";
application.start();
  • main-page.ts
import {SpotifyDemo} from "./main-view-model";

function pageLoaded(args) {
  var page = args.object;
  page.bindingContext = new SpotifyDemo();
}
exports.pageLoaded = pageLoaded;
  • main-view-model.ts
import {Observable, EventData} from 'data/observable';
import {Page} from 'ui/page';
import {topmost} from 'ui/frame';
import {AnimationCurve} from 'ui/enums';
import * as loader from 'nativescript-loading-indicator';
import {TNSSpotifyConstants, TNSSpotifyAuth, TNSSpotifyPlayer, TNSSpotifyPlaylist, TNSSpotifyRequest, Utils} from 'nativescript-spotify';

export class SpotifyDemo extends Observable {
  private _spotify: TNSSpotifyPlayer;

  constructor() {
    super();
    
    this._spotify = new TNSSpotifyPlayer();
    
    // when using iOS delegates that extend NSObject, TypeScript constructors are not used, therefore a separate `initPlayer()` exists
    this._spotify.initPlayer(true); // passing `true` lets player know you want it to emit events (sometimes it's not desired)
    
    // small sample of events (see Documentation below for full list)
    this._spotify.audioEvents.on('albumArtChange', (eventData) => {
      this.updateAlbumArt(eventData.data.url);
    });
    this._spotify.audioEvents.on('authLoginSuccess', (eventData) => {
      this.loginSuccess();
    });
  }
  
  public login() {
    TNSSpotifyAuth.LOGIN();
  }
  
  public play(args?: EventData) {
    this._spotify.togglePlay('spotify:track:58s6EuEYJdlb0kO7awm3Vp').then((isPlaying: boolean) => {
      console.log(isPlaying ? 'Playing!' : 'Paused!');
    }, (error) => {
      console.log(`Playback error: ${error}`);
    });
  }
  
  private updateAlbumArt(url: string) {
    this.set(`currentAlbumUrl`, url);
  }
  
  private loginSuccess() {
    console.log(`loginSuccess!`);
  } 
}

Screenshots

Sample 1Sample 2
Sample1Sample2
Sample 3Sample 4
Sample3Sample4

Android

Setup

  • Docs coming soon for Android...

Documentation

TNSSpotifyPlayer

TNSSpotifyPlayer implements SPTAudioStreamingPlaybackDelegate.

Creating:

// Option 1: simple
this.spotify = new TNSSpotifyPlayer();
this.spotify.initPlayer();

// Option 2: advanced
this.spotify = new TNSSpotifyPlayer();
// passing `true` will let the player know it should emit events
this.spotify.initPlayer(true);

// it allows you to listen to events like so:
this.spotify.audioEvents.on('startedPlayingTrack', (event) => {
  console.log(event.data.url); // spotify track url
});

// play/pause a track
this.spotify.togglePlay('spotify:track:58s6EuEYJdlb0kO7awm3Vp').then((isPlaying: boolean) => {
  console.log(isPlaying ? 'Playing!' : 'Paused!');
}, (error) => {
  console.log(`Playback error: ${error}`);
});

Methods

MethodDescription
togglePlay(track?: string): Promise<any>Allows toggle play/pause on a track, or changing a track. track must be a valid spotify track uri. Learn more here
isPlaying(): booleanDetermine if player is currently playing
isLoggedIn(): booleanDetermine if player is authenticated
setVolume(value: number): Promise<any>Set the player volume
loadedTrack(): stringDetermine current loaded track (spotify track uri)
currentTrackMetadata(): ISpotifyTrackMetadataGet the current track's metadata. Learn more here

Events

EventDescription
authLoginChangeSends along data = status: boolean When auth state changes.
authLoginCheckWhen auth callback has returned and is verifying authentication
authLoginSuccessWhen auth succeeded
albumArtChangeSends along data = url: string When track triggers a play start, this will also trigger to send along the correct album art of the track.
playerReadyWhen the session has been validated and the player is ready to play.
changedPlaybackStatusSends along data = playing: boolean When playback state changes.
seekedToOffsetSends along data = offset: number When player has seeked to a given offset.
changedVolumeSends along data = volume: number When the player volume was changed.
changedShuffleStatusSends along data = shuffle: number When shuffle setting was changed.
changedRepeatStatusSends along data = repeat: number When repeat setting was changed.
changedToTrackSends along data = metadata: any When track change occurs.
failedToPlayTrackSends along data = url: string When track play fails. Provides the url of the track that failed.
startedPlayingTrackSends along data = url: string When track play starts. Provides the url of the track that started.
stoppedPlayingTrackSends along data = url: string When track play stops. Provides the url of the track that stopped.
skippedToNextTrackWhen player skipped to next track.
skippedToPreviousTrackWhen player skipped to previous track.
activePlaybackDeviceWhen the audio streaming object becomes the active playback device on the user’s account.
inactivePlaybackDeviceWhen the audio streaming object becomes an inactive playback device on the user’s account.
poppedQueueWhen the audio streaming object becomes an inactive playback device on the user’s account.
temporaryConnectionErrorA temporary connection error occurred.
streamErrorSends along data = error: any when a streaming error occurred.
receivedMessageSends along data = message: string when a message is received from the Spotify service.
streamDisconnectedWhen the stream becomes disconnected.

TNSSpotifyAuth

TNSSpotifyAuth

Provides static properties and methods to help with authentication handling and user management.

Properties

PropertyDescription
REDIRECT_URL: stringUsed to set your spotify application redirect url, required for device auth redirect, ie: 'your-app-custom-url-scheme://spotifylogin'
SESSION: SPTSessionRepresents the current auth session.
CLEAR_COOKIES: booleanClear cookies in auth window to not remember last logged in user. Defaults false.
PREMIUM_MSG: stringThe message which alerts when a non-premium user attempts to play a track.

Methods

MethodDescription
LOGIN(): voidInitiates login sequence.
LOGIN_WITH_SESSION(session): voidLogs user in with session returned from the in-app browser auth window.
LOGOUT(): voidClear's persisted user session and notifies of login change.
HANDLE_AUTH_CALLBACK(url): booleanWhen using standard browser redirect auth, this can be used in application launch phase to handle the auth redirect back into the app. On older versions, this may be needed.
VERIFY_SESSION(session?: any): Promise<any>Mainly used internally, but used to restore a session from local persistence and/or renew.
SAVE_SESSION(session): voidMainly used internally, but can be used to persist a valid Spotify session.
GET_STORED_SESSION(): anyGet the current user's session. Learn more here
RENEW_SESSION(session): Promise<any>Can be used to pass an expired session to renew it.
CURRENT_USER(): Promise<any>Get the current user object. Learn more here

TNSSpotifySearch

TNSSpotifyAuth

Provides 1 static method to search Spotify.

Methods

MethodDescription
QUERY(query: string, queryType: string, offset: number = 0): Promise<any>Search and paginate through query results of Spotify search results. Resolves an Object structure: {page: number (offset), hasNextPage: boolean, totalListLength: number, tracks: Array}. Right now using queryType = 'track' is supported. More query types coming soon.

Why the TNS prefixed name?

TNS stands for Telerik NativeScript

iOS uses classes prefixed with NS (stemming from the NeXTSTEP days of old): https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/

To avoid confusion with iOS native classes, TNS is used instead.

License

MIT

1.6.1

8 years ago

1.6.0

8 years ago

1.5.11

8 years ago

1.5.10

8 years ago

1.5.9

8 years ago

1.5.8

8 years ago

1.5.7

8 years ago

1.5.6

8 years ago

1.5.5

8 years ago

1.5.4

8 years ago

1.5.3

8 years ago

1.5.2

8 years ago

1.5.1

8 years ago

1.5.0

8 years ago

1.4.9

8 years ago

1.4.8

8 years ago

1.4.7

8 years ago

1.4.6

8 years ago

1.4.5

8 years ago

1.4.4

8 years ago

1.4.3

8 years ago

1.4.2

8 years ago

1.4.1

8 years ago

1.4.0

8 years ago

1.3.8

8 years ago

1.3.7

8 years ago

1.3.6

8 years ago

1.3.5

8 years ago

1.3.4

8 years ago

1.3.3

8 years ago

1.3.2

8 years ago

1.3.1

8 years ago

1.3.0

8 years ago

1.2.6

8 years ago

1.2.5

8 years ago

1.2.4

8 years ago

1.2.3

8 years ago

1.2.1

8 years ago

1.2.0

8 years ago

1.1.0

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago