Skip to content

How To: Listen To Librespot Events

Julian K edited this page Jul 8, 2023 · 4 revisions

librespot supports the --onevent flag to pass the path to a script to be run on every event that is dispatched.

Information about the event such as it's name and possibly others are passed as environment variables from librespot:

#!/bin/bash

echo Spotify Event:
echo PLAYER_EVENT: $PLAYER_EVENT
echo TRACK_ID:     $TRACK_ID
echo OLD_TRACK_ID: $OLD_TRACK_ID

To use this, simply add the following to your config in /etc/raspotify/conf:

# script name passed to the --onevent flag, make sure raspotify has permissons call this script or you'll get an error
LIBRESPOT_ONEVENT="/usr/bin/yourscripthere.sh"

# you can even pass parameters as environment variables, you'll have access to those in your script
MY_SECRET_PASSWORD="muhahaha"

Reload raspotify with sudo systemctl restart raspotify.service and now your script will be called on an every event.

Available Events and Variables

Raspotify uses it's own vendored version of librespot, which means not all events and variables in the upstream repo are available. Refer to the implementation to find out what is and what is not available in raspotify.

// ...
Ok(new_id) => {
  env_vars.insert("PLAYER_EVENT", "changed".to_string());
  env_vars.insert("OLD_TRACK_ID", old_id);
  env_vars.insert("TRACK_ID", new_id);
}
// ..:

Related information:

Librespot #1160: Event System overehauled, not yet released

Example: Turn on Sound System over MQTT

The following example turns on a Tasmota Smart Switch when a client connects to raspotify.

#!/bin/bash

# Sends 'ON' to the MQTT Topic of my Tasmota smart switch telling it to turn on my sound system
# depends on 'mosquitto-clients' for 'mosquitto_pub' command
#
# the following is set in '/etc/raspotify/conf' to run this script and pass the relevant variables:
#
# LIBRESPOT_ONEVENT="/usr/bin/soundsystem-on.sh" # copy script here so librespot can find it
# MQTT_BROKER="your broker ip/url here"
# MQTT_USER="your mqtt user here"
# MQTT_PASS="your password"
# MQTT_TOPIC="cmnd/<tasmota name>/Power"

# 'started' for librespot <=0.4.2; 'session_connected' for librespot > 0.4.2
if [ $PLAYER_EVENT = "started" ] || [ $PLAYER_EVENT = "session_connected" ]; then
  mosquitto_pub -h $MQTT_BROKER -u $MQTT_USER -P $MQTT_PASS -t $MQTT_TOPIC -m "ON"
  echo "Sent 'ON' to $MQTT_TOPIC to turn on sound system"
fi