Skip to content

Instantly share code, notes, and snippets.

@hoehermann
Last active November 13, 2024 00:22
Show Gist options
  • Save hoehermann/8b6fa0682bd9192e835d1b7ba8daa4b6 to your computer and use it in GitHub Desktop.
Save hoehermann/8b6fa0682bd9192e835d1b7ba8daa4b6 to your computer and use it in GitHub Desktop.
This script mutes Spotify when it plays advertisements.
#!/usr/bin/env python3
# encoding: utf-8
import sys
import dbus
import dbus.mainloop.glib
import subprocess
import time
import re
from gi.repository import GLib
import pulsectl # https://github.com/mk-fg/python-pulse-control
def pulse_mute_spotify(mutestate):
with pulsectl.Pulse('spotisilencer') as pulse:
for sink_input in pulse.sink_input_list():
# sink_input.name in ['Spotify', 'Playback'] is ambiguous
binary = sink_input.proplist.get('application.process.binary', None)
if (binary == 'spotify'):
pulse.sink_input_mute(sink_input.index, mutestate)
print(f'Set mutestate to {mutestate} for sink ({sink_input}) of {binary}.')
def is_advert(metadata):
""" Whether the current song is an advertisement. """
if 'Metadata' in metadata:
m = metadata['Metadata']
artist = m['xesam:artist'][0]
return artist == ""
else:
return False
def propertiesChanged_handler(sender=None, metadata=None, sig=None):
time.sleep(0.5) # event comes a bit earlier than actual content change
is_ad = is_advert(metadata)
pulse_mute_spotify(is_ad)
def main():
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
try:
remote_object = bus.get_object(
"org.mpris.MediaPlayer2.spotify",
"/org/mpris/MediaPlayer2"
)
change_manager = dbus.Interface(
remote_object,
'org.freedesktop.DBus.Properties'
)
change_manager.connect_to_signal(
"PropertiesChanged",
propertiesChanged_handler
)
except dbus.exceptions.DBusException as dbe:
if (dbe.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown"):
print(f"Please start Spotify first. ({dbe.get_dbus_message()})")
sys.exit(1)
loop = GLib.MainLoop()
loop.run()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment