GithubHelp home page GithubHelp logo

labystudio / java-spotify-api Goto Github PK

View Code? Open in Web Editor NEW
14.0 2.0 5.0 160 KB

Spotify API written in Java to locally access the current song information

Java 100.00%
java lyrics position song spotify spotify-api track linux macos windows

java-spotify-api's Introduction

Banner

A Spotify API written in Java to access the current playing song.
There is no need for an access token, any internet connection or a premium account because the API reads the information directly from the application itself.

Feature Overview

  • Track id
  • Track title & artist
  • Track progress & length
  • Playing state (Playing, paused)
  • Track cover
  • Media keys (Previous song, play/pause & next song)

Supported operating systems:

  • Windows
  • macOS
  • Linux distros that uses systemd

Gradle Setup

repositories {
    maven { url 'https://jitpack.io' }
}

dependencies {
    implementation 'com.github.LabyStudio:java-spotify-api:+:all'
}

Example

Create the API and get the current playing song and position:

// Create a new SpotifyAPI for your operating system
SpotifyAPI api = SpotifyAPIFactory.createInitialized();

// It has no track until the song started playing once
if (api.hasTrack()) {
    System.out.println(api.getTrack());
}

// It has no position until the song is paused, the position changed or the song changed
if (api.hasPosition()) {
    System.out.println(api.getPosition());
}

Register a listener to get notified when the song changes:

SpotifyAPI api = SpotifyAPIFactory.create();
api.registerListener(new SpotifyListener() {
    @Override
    public void onConnect() {
        System.out.println("Connected to Spotify!");
    }
    
    @Override
    public void onTrackChanged(Track track) {
        System.out.printf("Track changed: %s (%s)\n", track, formatDuration(track.getLength()));
    }
    
    @Override
    public void onPositionChanged(int position) {
        if (!api.hasTrack()) {
            return;
        }
        
        int length = api.getTrack().getLength();
        float percentage = 100.0F / length * position;
        
        System.out.printf(
            "Position changed: %s of %s (%d%%)\n",
            formatDuration(position),
            formatDuration(length),
            (int) percentage
        );
    }
    
    @Override
    public void onPlayBackChanged(boolean isPlaying) {
        System.out.println(isPlaying ? "Song started playing" : "Song stopped playing");
    }
    
    @Override
    public void onSync() {
        
    }
    
    @Override
    public void onDisconnect(Exception exception) {
        System.out.println("Disconnected: " + exception.getMessage());
        
        // api.stop();
    }
});

// Initialize the API
api.initialize();

Fetch an image of the current playing track:

// Create an instance of the Open Spotify API (Or use SpotifyAPI#getOpenAPI)
OpenSpotifyAPI openSpotifyAPI = new OpenSpotifyAPI();

// Download the cover art of the current song
BufferedImage imageTrackCover = openSpotifyAPI.requestImage(track);

You can also skip the current song using the Media Key API:

SpotifyAPI api = SpotifyAPIFactory.createInitialized();

// Send media key to the operating system
api.pressMediaKey(MediaKey.NEXT);

java-spotify-api's People

Contributors

holybaechu avatar jumpingpxl avatar labystudio avatar princessakira avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

java-spotify-api's Issues

Invalid trackID

When using, i can observe an invalid track id.
This will cause the following error

java.lang.NullPointerException: Cannot read field "id" because "openTrack" is null
	at de.labystudio.spotifyapi.open.OpenSpotifyAPI.requestOpenTrack(OpenSpotifyAPI.java:247)
	at de.labystudio.spotifyapi.platform.windows.WinSpotifyAPI.onTick(WinSpotifyAPI.java:75)
	at de.labystudio.spotifyapi.platform.AbstractTickSpotifyAPI.onInternalTick(AbstractTickSpotifyAPI.java:69)
	at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539)
	at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
	at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
	at java.base/java.lang.Thread.run(Thread.java:833)

I attached a screenshot of my IDE below
image
image

onPositionChanged and onPlaybackChanged not updating

After using most of the documentation code:

Main.java:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");

        SpotifyController controller = new SpotifyController("http://192.168.188.74/api/custom?name=Spotify");

        controller.register();


    }
}

SpotifyController.java

import de.labystudio.spotifyapi.SpotifyAPI;
import de.labystudio.spotifyapi.SpotifyAPIFactory;
import de.labystudio.spotifyapi.SpotifyListener;
import de.labystudio.spotifyapi.model.Track;

public class SpotifyController 
{   


    private SpotifyAPI spotify;
    Httpcontroller httpcontroller;

    SpotifyController(String url)
    {
        spotify = SpotifyAPIFactory.create();
        httpcontroller = new Httpcontroller("http://192.168.188.74/api/custom?name=Spotify");
    }

    public void register()
    {
        spotify.registerListener(new SpotifyListener() 
        {
        
            @Override
            public void onConnect() {
                System.out.println("Connected to Spotify!");
            }
            
            @Override
            public void onTrackChanged(Track track) {
                System.out.println("Track changed:" + track);
            }
            
            @Override
            public void onPositionChanged(int position) {
                /*if (!spotify.hasTrack()) {
                    return;
                }
                
                int length =spotify.getTrack().getLength();
                float percentage = 100.0F / length * position;
                
                System.out.printf(
                    "Position changed: %s of %s (%d%%)\n",
                    formatDuration(position),
                    formatDuration(length),
                    (int) percentage
                );*/

                System.out.println("Position change: " + position);
            }
            
            @Override
            public void onPlayBackChanged(boolean isPlaying) {
                System.out.println(isPlaying ? "Song started playing" : "Song stopped playing");
            }
            
            @Override
            public void onSync() {
                
            }
            
            @Override
            public void onDisconnect(Exception exception) {
                System.out.println("Disconnected: " + exception.getMessage());
                
                spotify.stop();
            }

        });

        spotify.initialize();
    }
    


}

Ive noticed it never prints "Song stopped playing" and "Position change" during songs, it only prints position change after skipping a song. Am I missing something or is this a bug?

Recent Spotify update broke the API

Apparently since the latest Spotify update, the API seems broken and does not work properly anymore.
I'm not getting any errors inside of LabyMod.

So I'm currently trying to get in contact with @PrincessAkira again to help out investigating, so we can maybe find the error, the reason for the error and then provide a fix for it in form as a PR.

Tested with Spotify version:
Spotify für Windows (64 Bit)
1.2.20.1216.ge7a7b92f

Need guidance on using java-spotify-api as a basic player.

I am relatively new to the Spotify API and am currently attempting to integrate it into my project as a basic player. Despite reviewing the documentation, I find myself unclear on the essential steps and requirements.

I have a few specific queries regarding the integration process:

  1. How do I establish a connection and link my application API with the Spotify API?
  2. I currently have three buttons to control playback in my GUI-based project developed with Ant.

Development Environment:

  • IDE: NetBeans 17
  • Java Version: 21
  • Build System: Ant

If any additional information is needed to better understand my situation, Please ask, I'll provide it.

Recent Spotify update broke the API (again)

Apparently since the latest Spotify update (again), the API seems broken and does not work properly anymore.
I'm not getting any errors inside of LabyMod.

I sent @PrincessAkira a message about this, so that a fix will be worked on.

Tested with Spotify version:
Spotify für Windows (64 Bit)
1.2.21.1104.g42cf0a50

Crashing with OSX

Caused by: java.lang.ClassNotFoundException: de.labystudio.spotifyapi.SpotifyListener

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at net.minecraftforge.fml.common.FMLModContainer.handleModStateEvent(FMLModContainer.java:560)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.google.common.eventbus.EventSubscriber.handleEvent(EventSubscriber.java:74)
at com.google.common.eventbus.SynchronizedEventSubscriber.handleEvent(SynchronizedEventSubscriber.java:47)
at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322)
at com.google.common.eventbus.EventBus.dispatchQueuedEvents(EventBus.java:304)
at com.google.common.eventbus.EventBus.post(EventBus.java:275)
at net.minecraftforge.fml.common.LoadController.sendEventToModContainer(LoadController.java:211)
at net.minecraftforge.fml.common.LoadController.propogateStateMessage(LoadController.java:189)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.google.common.eventbus.EventSubscriber.handleEvent(EventSubscriber.java:74)
at com.google.common.eventbus.SynchronizedEventSubscriber.handleEvent(SynchronizedEventSubscriber.java:47)
at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322)
at com.google.common.eventbus.EventBus.dispatchQueuedEvents(EventBus.java:304)
at com.google.common.eventbus.EventBus.post(EventBus.java:275)
at net.minecraftforge.fml.common.LoadController.distributeStateMessage(LoadController.java:118)
at net.minecraftforge.fml.common.Loader.preinitializeMods(Loader.java:556)

Caused by: java.lang.NullPointerException

... 16 more

Caused by: java.lang.ClassNotFoundException: de.labystudio.spotifyapi.SpotifyListener
at net.minecraft.launchwrapper.LaunchClassLoader.findClass(LaunchClassLoader.java:191)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
... 44 more
coremods are present:

Caused by: java.lang.NullPointerException
at net.minecraft.launchwrapper.LaunchClassLoader.findClass(LaunchClassLoader.java:182)
... 46 more

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.