Skip to content

ServiceAndScripting

Josh Shepherd edited this page Jun 24, 2021 · 2 revisions

C# Scripting

The main SpotifyService script is setup to be a SceneSingleton meaning once loaded, the object will persist using DontDestroyOnLoad, unless destroyed.

After authorization anywhere in your code, you can access the current SpotifyService by calling the static SpotifyService.Instance property.

You can also call the GetSpotifyClient() function on the SpotifyService instance to get the SpotifyAPI-NET's SpotifyClient.

SpotifyClient client = SpotifyService.Instance.GetSpotifyClient();
if (client != null)
{
  var userProfile = await client.UserProfile.Current();
}
else
{
  Debug.LogError("Client is null and not yet initialized.");
}

Helper Base Classes

Spotify4Unity also provides helper base classes for help with callbacks within the SpotifyService. All helpers can be found here: Spotify4Unity/Assets/Spotify4Unity/Unity

SpotifyServiceListener

A simple base class setup to listen for when the SpotifyService has connected and provides an overridable function.

using SpotifyAPI.Web;
using UnityEngine;

public class ExampleListener : SpotifyServiceListener
{
    protected override void OnSpotifyConnectionChanged(SpotifyClient client)
    {
        base.OnSpotifyConnectionChanged(client);

        if (client == null)
        {
            Debug.Log("User has signed out, been deauthorised or lost connection to Spotify API");
        }
        else
        {
            Debug.Log("User has authorized connection to the Spotify API");
        }
    }
}

SpotifyPlayerListener

A more advanced base class used to listen to the current context of Spotify and detect changes of the current track. The class provides an event OnPlayingItemChanged as well as an overridable function PlayingItemChanged(IPlayableItem item) that is triggered when the Spotify context's item changes.

The SpotifyPlayerListener contains a thread that constantly fetches the latest context. The update frequency can be set using the UpdateFrequencyMS property. I suggest not going any lower than 1000 milliseconds.

using SpotifyAPI.Web;
using UnityEngine;

public class ExamplePlayerListener : SpotifyPlayerListener
{
    protected override void PlayingItemChanged(IPlayableItem item)
    {
        base.PlayingItemChanged(item);

        if (item is FullTrack newTrack)
        {
            string artistsString = S4UUtility.ArtistsToSeparatedString(", ", newTrack.Artists);
            Debug.Log($"New track is {artistsString} - {newTrack.Name}");
        }
        else if (item is FullEpisode fullEpisode)
        {
            Debug.Log($"New episode is {fullEpisode.Show.Publisher} - {fullEpisode.Show.Name}");
        }
        else
        {
            Debug.Log("Track is null!");
        }
    }
}