Skip to content

Instantly share code, notes, and snippets.

@Riztard
Forked from engelmarkus/test.py
Last active January 20, 2023 11:10
Show Gist options
  • Save Riztard/6f940ed4b7c4beb4cbb65bc99af1b2a9 to your computer and use it in GitHub Desktop.
Save Riztard/6f940ed4b7c4beb4cbb65bc99af1b2a9 to your computer and use it in GitHub Desktop.
[POC] Auto-stopping Spotify while other programs play audio
#!/usr/bin/env python
# pip install dbus-python pulsectl
import signal
import sys
import pulsectl
import dbus
import time
import threading
def sig_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, sig_handler)
session_bus = dbus.SessionBus()
spotify = session_bus.get_object('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2')
player_iface = dbus.Interface(spotify, 'org.mpris.MediaPlayer2.Player')
props_iface = dbus.Interface(spotify, 'org.freedesktop.DBus.Properties')
with pulsectl.Pulse('my-client') as pulse:
spotify_sink_input = next(filter(lambda si: 'Spotify' in si.name, pulse.sink_input_list()))
spotify_status = props_iface.Get('org.mpris.MediaPlayer2.Player', 'PlaybackStatus')
def event_handler(ev):
event_handler.index = ev.index
raise pulsectl.PulseLoopStop
pulse.event_mask_set('sink_input')
pulse.event_callback_set(event_handler)
continue_resuming=False
def function():
global continue_resuming
continue_resuming=False
uncorked = filter(lambda si: not 'Spotify' in si.name and not si.corked, sink_inputs)
spotify_status = props_iface.Get('org.mpris.MediaPlayer2.Player', 'PlaybackStatus')
if len(list(uncorked)) > 0:
if spotify_status == 'Playing':
player_iface.Pause()
else:
continue_resuming = True
time.sleep(3)
if continue_resuming and spotify_status == 'Paused':
player_iface.Play()
continue_resuming=False
while True:
pulse.event_listen(timeout = 0)
if spotify_sink_input.index == event_handler.index:
continue
sink_inputs = pulse.sink_input_list()
threading.Thread(target=function).start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment