kRYOoX kRYOoX - 1 year ago 143
Linux Question

Get spotify currently playing track

EDIT : Let's try to clarify all this.

I'm writing a python script, and I want it to tell me the song that Spotify is currently playing.

I've tried looking for libraries that could help me but didn't find any that are still maintained and working.
I've also looked through Spotify's web API, but it does not provide any way to get that information.

The only potential solution I found would be to grab the title of my Spotify (desktop app) window. But I didn't manage to do that so far.

So basically, what I'm asking is whether anyone knows :

  • How to apply the method I'm already trying to use (get the window's title from a program), either in pure python or using an intermediary shell script.


  • Any other way to extract that information from Spotify's desktop app or web client.

Original post :

I'm fiddling with the idea of a python status bar for a linux environment, nothing fancy, just a script tailored to my own usage. What I'm trying to do right now is to display the currently playing track from spotify (namely, the artist and title).

There does not seem to be anything like that in their official web API. I haven't found any third party library that would do that either. Most libraries I found are either deprecated since spotify released their current API, or they are based on said API which does not do what I want.

I've also read a bunch of similar question in here, most of which had no answers, or a deprecated solution.

I thought about grabbing the window title, since it does diplay the information I need. But not only does that seem really convoluted, I also have difficulties making this happen. I was trying to get it by running a combination of the linux commands xdotools and xprop inside my script.

It's worth mentionning that since I'm already using the psutil lib for other informations, I already have access to spotify's PID.

Any idea how I could do that ?

And in case my method was the only one you can think of, any idea how to actually make it work ?

Your help will be appreciated.

Answer Source

The Spotify client on Linux implements a D-Bus interface called MPRIS - Media Player Remote Interfacing Specification.

You could access the title (and other metadata) from python like this:

import dbus
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify",
spotify_properties = dbus.Interface(spotify_bus,
metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata")

# The property Metadata behaves like a python dict
for key, value in metadata.items():
    print key, value

# To just print the title
print metadata['xesam:title']

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download