Spotify Ad Mute for Sonos (external Python script)

This automation consists of three components:

1. Spotify Client running on your server (Linux)
On the Spotify Desktop Client, I can connect directly to my Sonos speakers, which gives me much more control over my music than the mobile app.
image

But that isn’t everything. Linux has a system component called DBus that allows applications to communicate with each other. The Spotify Client on Linux also has a DBus interface, which allows the users to play and pause media, get metadata of the current song, and much more.

2. Python script
sonos-admute.py

import dbus
import requests

class SpotifyDBus():
    def __init__(self):
        self.session_bus = dbus.SessionBus()

    def get_dbus_object(self):
        return self.session_bus.get_object('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2')

    def get_metadata(self):
        try:
            interface = dbus.Interface(self.get_dbus_object(), 'org.freedesktop.DBus.Properties')
            return interface.Get('org.mpris.MediaPlayer2.Player', 'Metadata')
        except Exception:
            return None


spotify = SpotifyDBus()
current_state = None
old_state = None

while True:
    metadata = spotify.get_metadata()

    if metadata == None:
        continue
    else:
        current_state = metadata['mpris:trackid']
        is_ad = metadata['mpris:trackid'].startswith('spotify:ad')

        if old_state != current_state:
            print(('\x1B[31m' if is_ad else '\x1B[32m') + (metadata['xesam:title'] or 'Unknown') + ' - ' + (metadata['xesam:artist'][0] or 'Unknown') + '\033[0m')
            requests.post('https://your.homeassistant:8123/api/webhook/' + ('spotify_mute' if is_ad else 'spotify_unmute'))

            old_state = current_state

(Should be cleaned up a bit)
This script needs to run on the same computer as the Spotify Client. It reads out the current track ID via the Spotify DBus interface and checks if an ad is playing. If so, it triggers a Webhook automation on my Home Assistant instance.
An ad is detected when the track ID starts with spotify:ad, if a normal song or a podcast is playing, the track ID would start with spotify:trackor spotify:podcast. I don’t use the title for the ad detection because ad titles aren’t always just Advertisement. Sometimes it’s just Ad, or the name of the advertised product or company.

3. The Home Assistant webhook automation
The automation actually only mutes or unmutes the Sonos media player when the Webhook event is received.

alias: Spotify Ad Mute
description: Stellt die Medienwiedergabe auf stumm, während Werbung läuft
trigger:
  - platform: webhook
    webhook_id: spotify_mute
    id: spotify_mute
  - platform: webhook
    webhook_id: spotify_unmute
    id: spotify_unmute
condition:
  - condition: device
    device_id: 12345
    domain: media_player
    entity_id: media_player.playbase
    type: is_playing
action:
  - choose:
      - conditions:
          - condition: trigger
            id: spotify_mute
        sequence:
          - service: media_player.volume_mute
            target:
              entity_id: media_player.playbase
            data:
              is_volume_muted: true
      - conditions:
          - condition: trigger
            id: spotify_unmute
        sequence:
          - service: media_player.volume_mute
            target:
              entity_id: media_player.playbase
            data:
              is_volume_muted: false
    default: []
mode: single

Sothis is how I avoid paying unnecessarily for a premium account and can still listen to music in peace. I hope I could help someone with this. :slight_smile:

1 Like