internal PlaylistContainer(IntPtr containerPtr, Session owningSession) { if(containerPtr == IntPtr.Zero) throw new ArgumentException("containerPtr can not be zero"); lock(libspotify.Mutex) { if(containers.ContainsKey(containerPtr)) throw new Exception("libspotify-sharp internal error, creating playlist container for the second time"); libspotify.sp_playlistcontainer_add_callbacks(containerPtr, callbacksPtr, IntPtr.Zero); this.owningSession = owningSession; this.containerPtr = containerPtr; containers.Add(containerPtr, this); for(int i = 0; i < PlaylistCount; i++) { IntPtr playlistPtr = IntPtr.Zero; playlistPtr = libspotify.sp_playlistcontainer_playlist(containerPtr, i); Playlist p = new Playlist(playlistPtr, owningSession); playlists.Add(p); playlistIndexByPtr.Add(playlistPtr, i); } } }
/// <summary> /// Initialises the Spotify Session /// </summary> /// <returns>The new Session instance</returns> public async Task<Session> Init() { // Create a session Session = await SpotiFire.Spotify.CreateSession( _key, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Touchee", "Spotify", "cache"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Touchee", "Spotify", "settings"), "Touchee" ); // Set props Session.PreferredBitrate = BitRate.Bitrate320k; // Set callbacks Session.ConnectionError += ConnectionError; Session.ConnectionstateUpdated += ConnectionstateUpdated; Session.CredentialsBlobUpdated += Session_CredentialsBlobUpdated; // Login if we have a username and credentials if (this.CredentialsStored) { string username = Plugin.Config.Get("username"); string credentials = Plugin.Config.Get("credentials"); this.Login(username, null, credentials); } // Return the session return Session; }
public SpotifyPlayer() { view = new MediaChrome.Spotify.SpotifyView(); Spocky.MyClass D = new Spocky.MyClass(); SpotifySession = Spotify.Session.CreateInstance(D.AppKey(), "SpofityCaches", "SpofityCaches", "LinSpot"); Application.EnableVisualStyles(); SpofityRuntime.Login sD = new SpofityRuntime.Login(this); if(sD.ShowDialog() == DialogResult.OK) { SpotifySession.LogInSync(sD.User,sD.Pass,new TimeSpan(4000)); } SpotifySession.OnConnectionError+= new SessionEventHandler(SpotifySession_OnConnectionError); SpotifySession.OnMusicDelivery+= new MusicDeliveryEventHandler(SpotifySession_OnMusicDelivery); SpotifySession.OnEndOfTrack+= new SessionEventHandler(SpotifySession_OnEndOfTrack); SpotifySession.OnPlaylistContainerLoaded+= new SessionEventHandler(SpotifySession_OnPlaylistContainerLoaded); SpotifySession.OnAlbumBrowseComplete+= new AlbumBrowseEventHandler(SpotifySession_OnAlbumBrowseComplete); SpotifySession.OnImageLoaded+= new ImageEventHandler(SpotifySession_OnImageLoaded); SpotifySession.PlaylistContainer.OnContainerLoaded += new PlaylistContainerEventHandler(PlaylistContainer_OnContainerLoaded); while (!playlistLoaded) { Thread.Sleep(100); } }
public static Playlist Create(Session session, Link link) { IntPtr ptr = libspotify.sp_playlist_create(session.sessionPtr, link.linkPtr); if (ptr != IntPtr.Zero) return new Playlist(ptr, session); else return null; }
/// <summary> /// Constructor /// </summary> /// <param name="session">The Spotify session to handle</param> public ContentsHandler(Session session) { _session = session; _session.ConnectionstateUpdated += ConnectionstateUpdated; var masterContainer = Touchee.Medium.Local.MasterContainer; if (masterContainer == null) Log("Master container for local medium not found. This should not happen!", Logger.LogLevel.Error); else _masterPlaylist = (Music.Media.MasterPlaylist)masterContainer; }
/// <summary> /// Called when the connection state of the session is updated. /// If the session is logged in, all present playlists are added and /// listeners are attached to the playlist collection list. /// </summary> async void ConnectionstateUpdated(Session sender, SessionEventArgs e) { switch (sender.ConnectionState) { // Logged out case ConnectionState.LoggedOut: if (_previousConnectionState == ConnectionState.LoggedIn) { // Remove all playlists MasterPlaylist.Instance.Dispose(); var playlists = Touchee.Medium.Local.Containers.OfType<Spotify.Media.Playlist>(); lock (playlists) { foreach (var playlist in playlists) playlist.Dispose(); } } break; // Offline state (when logged in, but not completely yet) case ConnectionState.Offline: break; // User has logged in case ConnectionState.LoggedIn: // Save the master playlist MasterPlaylist.Instance.Save(); // Wait for the playlist container await _session.PlaylistContainer; // Track initial set of playlists and starred list Log("PL: " + _session.PlaylistContainer.Playlists.Count); this.AddPlaylists(_session.PlaylistContainer.Playlists); this.AddPlaylist(_session.Starred); // Add event handler for removal/adding of playlists _session.PlaylistContainer.Playlists.CollectionChanged += Playlists_CollectionChanged; break; // User has been disconnected after having been logged in case ConnectionState.Disconnected: break; // No clue case ConnectionState.Undefined: break; } _previousConnectionState = sender.ConnectionState; }
void SpotifySession_OnMusicDelivery(Session sender, MusicDeliveryEventArgs e) { if (e.Samples.Length > 0) { if (player == null) { //player = new AlsaPlayer(e.Rate / 2); // Buffer 500ms of audio player = new BassPlayer(); Console.WriteLine("Player created"); } // Don't forget to set how many frames we consumed e.ConsumedFrames = player.EnqueueSamples(new AudioData(e.Channels, e.Rate-12, e.Samples, e.Frames)); /*X.Maximum = (float)currentTrack.Duration; X.Value +=10;*/ } else { e.ConsumedFrames = 0; } }
void SpotifySession_OnImageLoaded(Session sender, ImageEventArgs e) { /* if (e.Image != null) { try { string d = GetAppString()+"\\covers\\"+e.State+".jpg"; e.Image.Save(d, System.Drawing.Imaging.ImageFormat.Jpeg); } catch { } }*/ }
void SpotifySession_OnEndOfTrack(Session sender, SessionEventArgs e) { //Console.WriteLine("End of music delivery. Flushing player buffer..."); Thread.Sleep(1500); // Samples left in player buffer. Player lags 500 ms playbackDone.Set(); try { NextTrack(); } catch { } // Console.WriteLine("Playback complete"); }
void SpotifySession_OnConnectionError(Session sender, SessionEventArgs e) { }
void HandleOnPlayTokenLost(Session sender, SessionEventArgs e) { #if DEBUG if (Log.IsWarnEnabled) Log.Warn("Play token lost"); #endif _playbackDone.Set(); }
/// <summary> /// Called when a connection error occurs /// </summary> void ConnectionError(Session sender, SessionEventArgs e) { Log("Spotify: Connection Error: " + e.Error.ToString(), Logger.LogLevel.Error); }
void HandleOnEndOfTrack(Session sender, SessionEventArgs e) { #if DEBUG if (Log.IsDebugEnabled) Log.Debug("End of music delivery."); #endif try { LameEncoder.Close(); LameEncoder = null; _playbackDone.Set(); } catch (Exception ex) { #if DEBUG if (Log.IsErrorEnabled) Log.Error("Exception", ex); #endif } }
static void HandleOnConnectionError(Session sender, SessionEventArgs e) { #if DEBUG if (Log.IsErrorEnabled) Log.Error("Connection error: " + e.Status); #endif }
void SpotifySession_OnPlaylistContainerLoaded(Session sender, SessionEventArgs e) { foreach(Spotify.Playlist PlsList in SpotifySession.PlaylistContainer.CurrentLists) { //toBeAdded.Enqueue(PlsList); } }
/// <summary> /// Called when the Session connection status is updated /// </summary> async void ConnectionstateUpdated(Session sender, SessionEventArgs e) { Log("Spotify: Connection state: " + sender.ConnectionState.ToString()); this.OnStateUpdated(); switch (sender.ConnectionState) { // Logged out case ConnectionState.LoggedOut: break; // Offline state (when logged in, but not completely yet) case ConnectionState.Offline: break; // User has logged in case ConnectionState.LoggedIn: break; // User has been disconnected after having been logged in case ConnectionState.Disconnected: break; // No clue case ConnectionState.Undefined: throw new NotImplementedException(); } }
/// <summary> /// Called when the credentials blob has been updated from the Spotify session. /// Stores the username and these credentials into the Spotify plugin config. /// </summary> void Session_CredentialsBlobUpdated(Session sender, SessionEventArgs e) { Plugin.Config.Set("username", sender.UserName); Plugin.Config.Set("credentials", e.Message); Plugin.Config.Save(); }
/// <summary> /// Login into Spotify with the given username and password or username and credentials. /// </summary> /// <param name="username">The username to login</param> /// <param name="password">The password to use</param> /// <param name="credentials">The stored credentials to use</param> /// <returns>The resulting error code</returns> public async Task<Error> Login(string username, string password, string credentials = null) { if (Session == null) { Session = await this.Init(); if (Session == null) return Error.OTHER_TRANSIENT; } if (Session.ConnectionState == ConnectionState.LoggedIn) { return Error.OK; } if (!_loggingIn) { _loggingIn = true; if (credentials == null) _loginError = await Session.Login(username, password, true); else _loginError = await Session.Login(username, credentials); _loggingIn = false; return _loginError; } return Error.OTHER_TRANSIENT; }
void SpotifySession_OnPlaylistContainerLoaded(Session sender, SessionEventArgs e) { if (playlists == null) { playlists = new List<MediaChrome.Views.Playlist>(); } foreach (Spotify.Playlist _Playlist in SpotifySession.PlaylistContainer.CurrentLists) { MediaChrome.Views.Playlist D = new MediaChrome.Views.Playlist(this, _Playlist.Name,_Playlist.LinkString, Host); D.ID = _Playlist.LinkString; D.Title = _Playlist.Name; playlists.Add(D); } playlistLoaded = true; }
void HandleOnLoginComplete(Session sender, SessionEventArgs e) { #if DEBUG if (Log.IsDebugEnabled) Log.Debug("HandleOnLoginComplete"); #endif try { #if DEBUG if (Log.IsDebugEnabled) Log.Debug("Login result: " + e.Status); #endif _loginOk = Session.ConnectionState == sp_connectionstate.LOGGED_IN; _loggedIn.Set(); } catch (Exception ex) { #if DEBUG if (Log.IsErrorEnabled) Log.Error("Exception", ex); #endif } }
public void SetStarred(Session session, bool starred) { CheckLoaded(); if (!isLoaded) return; IntPtr arrayPtr = IntPtr.Zero; try { int[] array = new int[] { trackPtr.ToInt32() }; int size = Marshal.SizeOf(arrayPtr) * array.Length; arrayPtr = Marshal.AllocHGlobal(size); Marshal.Copy(array, 0, arrayPtr, array.Length); libspotify.sp_track_set_starred(session.sessionPtr, arrayPtr, 1, starred); } finally { if (arrayPtr != IntPtr.Zero) { Marshal.FreeHGlobal(arrayPtr); } } }
void Program_SpotifySession_OnLoginComplete(Session sender, SessionEventArgs e) { if(e.Status == sp_error.OK) { this.DialogResult= DialogResult.OK; //this.Close(); } else { //label6.Text = e.Status.ToString(); panel1.Show(); } }
static void HandleOnMessageToUser(Session sender, SessionEventArgs e) { #if DEBUG if (Log.IsInfoEnabled) Log.Info("Spotify says: " + e.Message); #endif }
internal static Session CreateInstance(byte[] applicationKey, string cacheLocation, string settingsLocation, string userAgent) { lock(libspotify.Mutex) { if(sessions.Count > 0) { throw new InvalidOperationException("libspotify can only handle one session at the moment"); } else { Session instance = new Session(applicationKey, cacheLocation, settingsLocation, userAgent); sessions.Add(instance.sessionPtr, instance); return instance; } } }
void HandleOnLoggedOut(Session sender, SessionEventArgs e) { #if DEBUG if (Log.IsDebugEnabled) Log.Debug("HandleOnLoggedOut"); #endif try { _playbackDone.Set(); _loggedOut.Set(); } catch (Exception ex) { #if DEBUG if (Log.IsErrorEnabled) Log.Error("Exception", ex); #endif } }
internal Playlist(IntPtr playlistPtr, Session owningSession) { if(playlistPtr == IntPtr.Zero) throw new ArgumentException("playlistPtr can not be zero"); lock(libspotify.Mutex) { this.playlistPtr = playlistPtr; this.owningSession = owningSession; libspotify.sp_playlist_add_callbacks(playlistPtr, callbacksPtr, IntPtr.Zero); playlists[playlistPtr] = this; } }
void HandleOnMusicDelivery(Session sender, MusicDeliveryEventArgs e) { try { // Write to LAME. LameEncoder.Write(e.Samples); // Don't forget to set how many frames we consumed e.ConsumedFrames = e.Frames; } catch (Exception ex) { #if DEBUG if (Log.IsErrorEnabled) Log.Error("Exception", ex); #endif } }
void SpotifySession_OnAlbumBrowseComplete(Session sender, AlbumBrowseEventArgs e) { /* string d = (string)e.State; string x = ""; int i=1; foreach(Track _Track in e.Result.Tracks) { x+="<treeitem>\n"; x+="<treerow uri=\""+_Track.LinkString+"\" id=\"track-"+i.ToString()+"\"> \n"; x+="<treecell value=\""+_Track.Name+"\"/>\n"; x+="<treecell value=\""+_Track.Artists[0].Name+"\"/>\n"; x+="<treecell type=\"progressbar\" value=\"0."+_Track.Popularity.ToString()+"\"/>\n"; x+="</treerow>\n"; x+="</treeitem>\n"; i++; } d = d.Replace("<Spotify:Album.Tracks/>",x); d = d.Replace("spotify:track","http://go.go/sp_play-spotify:track"); d = d.Replace("http://open.spotify.com/track/","http://go.go/sp_play-spotify:track:"); using(StreamWriter SW = new StreamWriter(Program.GetAppString()+"\\views\\"+X.app+"\\main.view.php")) { SW.Write(d); SW.Close(); } X.Times();*/ }
void HandleOnSearchComplete(Session sender, SearchEventArgs e) { #if DEBUG if (Log.IsDebugEnabled) Log.Debug("HandleOnSearchComplete"); #endif try { #if DEBUG if (Log.IsDebugEnabled) Log.Debug("Search returned: " + e.Result.TotalTracks + " tracks."); #endif foreach (Track track in e.Result.Tracks) _searchResults.Add(track); _searchComplete.Set(); } catch (Exception ex) { #if DEBUG if (Log.IsErrorEnabled) Log.Error("Exception", ex); #endif } }
static void HandleOnConnectionError(Session sender, SessionEventArgs e) { Console.WriteLine("Connection error: " + e.Status); }