Created
January 25, 2021 14:11
-
-
Save stoph/41590767c6d86c83484b866cc987031f to your computer and use it in GitHub Desktop.
Pi Bluetooth Media Control
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dbus, dbus.mainloop.glib, sys | |
from gi.repository import GLib | |
def on_property_changed(interface, changed, invalidated): | |
if interface != 'org.bluez.MediaPlayer1': | |
return | |
for prop, value in changed.items(): | |
if prop == 'Status': | |
print('Playback Status: {}'.format(value)) | |
elif prop == 'Track': | |
print('Music Info:') | |
for key in ('Title', 'Artist', 'Album'): | |
print(' {}: {}'.format(key, value.get(key, ''))) | |
def on_playback_control(fd, condition): | |
str = fd.readline() | |
if str.startswith('play'): | |
player_iface.Play() | |
elif str.startswith('pause'): | |
player_iface.Pause() | |
elif str.startswith('next'): | |
player_iface.Next() | |
elif str.startswith('prev'): | |
player_iface.Previous() | |
elif str.startswith('vol'): | |
vol = int(str.split()[1]) | |
if vol not in range(0, 128): | |
print('Possible Values: 0-127') | |
return True | |
transport_prop_iface.Set( | |
'org.bluez.MediaTransport1', | |
'Volume', | |
dbus.UInt16(vol)) | |
return True | |
if __name__ == '__main__': | |
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) | |
bus = dbus.SystemBus() | |
obj = bus.get_object('org.bluez', "/") | |
mgr = dbus.Interface(obj, 'org.freedesktop.DBus.ObjectManager') | |
player_iface = None | |
transport_prop_iface = None | |
for path, ifaces in mgr.GetManagedObjects().items(): | |
if 'org.bluez.MediaPlayer1' in ifaces: | |
player_iface = dbus.Interface( | |
bus.get_object('org.bluez', path), | |
'org.bluez.MediaPlayer1') | |
elif 'org.bluez.MediaTransport1' in ifaces: | |
transport_prop_iface = dbus.Interface( | |
bus.get_object('org.bluez', path), | |
'org.freedesktop.DBus.Properties') | |
if not player_iface: | |
sys.exit('Error: Media Player not found.') | |
if not transport_prop_iface: | |
sys.exit('Error: DBus.Properties iface not found.') | |
bus.add_signal_receiver( | |
on_property_changed, | |
bus_name='org.bluez', | |
signal_name='PropertiesChanged', | |
dbus_interface='org.freedesktop.DBus.Properties') | |
GLib.io_add_watch(sys.stdin, GLib.IO_IN, on_playback_control) | |
GLib.MainLoop().run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From https://scribles.net/controlling-bluetooth-audio-on-raspberry-pi/