python - 让信号在 PulseAudio 的 DBus 接口(interface)上工作?

标签 python dbus pulseaudio

我正在尝试让 D-Bus 信号处理程序在 PulseAudio 中接收器的状态发生变化(例如变为非事件状态)时被调用。不幸的是,它没有被调用,坦率地说,我不确定为什么。

import dbus
import dbus.mainloop.glib
from gi.repository import GObject


dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()


def signal_handler(*args, **kwargs):
    print('sig: ', args, kwargs)


def connect():
    import os
    if 'PULSE_DBUS_SERVER' in os.environ:
        address = os.environ['PULSE_DBUS_SERVER']
    else:
        bus = dbus.SessionBus()
        server_lookup = bus.get_object("org.PulseAudio1", "/org/pulseaudio/server_lookup1")
        address = server_lookup.Get("org.PulseAudio.ServerLookup1", "Address", dbus_interface="org.freedesktop.DBus.Properties")

    return dbus.connection.Connection(address)


conn = connect()
core = conn.get_object(object_path='/org/pulseaudio/core1')
core.connect_to_signal('StateUpdated', signal_handler)
core.ListenForSignal('org.PulseAudio.Core1.Device.StateUpdated', dbus.Array(signature='o'), dbus_interface='org.PulseAudio.Core1')
loop = GObject.MainLoop()
loop.run()

最佳答案

试试这个,对我有用。

import dbus
import os
from dbus.mainloop.glib import DBusGMainLoop
import gobject
def pulse_bus_address():
    if 'PULSE_DBUS_SERVER' in os.environ:
        address = os.environ['PULSE_DBUS_SERVER']
    else:
        bus = dbus.SessionBus()
        server_lookup = bus.get_object("org.PulseAudio1", "/org/pulseaudio/server_lookup1")
        address = server_lookup.Get("org.PulseAudio.ServerLookup1", "Address", dbus_interface="org.freedesktop.DBus.Properties")
        print(address)

    return address

def sig_handler(state):
    print("State changed to %s" % state)
    if state == 0:
        print("Pulseaudio running.")
    elif state == 1:
        print("Pulseaudio idle.")
    elif state == 2:
        print("Pulseaudio suspended")

# setup the glib mainloop

DBusGMainLoop(set_as_default=True)

loop = gobject.MainLoop()

pulse_bus = dbus.connection.Connection(pulse_bus_address())
pulse_core = pulse_bus.get_object(object_path='/org/pulseaudio/core1')
pulse_core.ListenForSignal('org.PulseAudio.Core1.Device.StateUpdated', dbus.Array(signature='o'), dbus_interface='org.PulseAudio.Core1')

pulse_bus.add_signal_receiver(sig_handler, 'StateUpdated')
loop.run()

要求 pulseaudio 的 default.pa 具有以下内容:

.ifexists module-dbus-protocol.so
load-module module-dbus-protocol
.endif

编辑: 对于那些想知道@conf-f-use 关于应用程序名称的问题的人。原来他们自己回答了这个问题,并把答案贴在这里:https://askubuntu.com/questions/906160/is-there-a-way-to-detect-whether-a-skype-call-is-in-progress-dbus-pulseaudio
窃取@con-f-use 的一段代码并将其应用于我上面的代码,我们得到一个监视器来跟踪状态是什么,并且能够告诉您应用程序名称、艺术家、标题和正在播放的名称。< br/> 欢呼@con-f-use :)

import dbus
import os
from dbus.mainloop.glib import DBusGMainLoop
import gobject
def pulse_bus_address():
    if 'PULSE_DBUS_SERVER' in os.environ:
        address = os.environ['PULSE_DBUS_SERVER']
    else:
        bus = dbus.SessionBus()
        server_lookup = bus.get_object("org.PulseAudio1", "/org/pulseaudio/server_lookup1")
        address = server_lookup.Get("org.PulseAudio.ServerLookup1", "Address", dbus_interface="org.freedesktop.DBus.Properties")
        print(address)

    return address

# convert byte array to string
def dbus2str(db):
    if type(db)==dbus.Struct:
        return str(tuple(dbus2str(i) for i in db))
    if type(db)==dbus.Array:
        return "".join([dbus2str(i) for i in db])
    if type(db)==dbus.Dictionary:
        return dict((dbus2str(k), dbus2str(v)) for k, v in db.items())
    if type(db)==dbus.String:
        return db+''
    if type(db)==dbus.UInt32:
        return str(db+0)
    if type(db)==dbus.Byte:
        return chr(db)
    if type(db)==dbus.Boolean:
        return db==True
    if type(db)==dict:
        return dict((dbus2str(k), dbus2str(v)) for k, v in db.items())
    return "(%s:%s)" % (type(db), db)

def sig_handler(state):
    print("State changed to %s" % state)
    if state == 0:
        print("Pulseaudio running.")
    elif state == 1:
        print("Pulseaudio idle.")
    elif state == 2:
        print("Pulseaudio suspended")

    dbus_pstreams = (
        dbus.Interface(
            pulse_bus.get_object(object_path=path),
            dbus_interface='org.freedesktop.DBus.Properties'
        ) for path in pulse_core.Get(
            'org.PulseAudio.Core1',
            'PlaybackStreams',
            dbus_interface='org.freedesktop.DBus.Properties' )
        )
    pstreams = {}
    for pstream in dbus_pstreams:
        try:
            pstreams[pstream.Get('org.PulseAudio.Core1.Stream', 'Index')] =  pstream
        except dbus.exceptions.DBusException:
            pass
    if pstreams:
        for stream in pstreams.keys():
            plist = pstreams[stream].Get('org.PulseAudio.Core1.Stream', 'PropertyList')
            appname = dbus2str(plist.get('application.name', None))
            artist = dbus2str(plist.get('media.artist', None))
            title = dbus2str(plist.get('media.title', None))
            name = dbus2str(plist.get('media.name', None))
            print appname,artist,title,name


# setup the glib mainloop

DBusGMainLoop(set_as_default=True)

loop = gobject.MainLoop()

pulse_bus = dbus.connection.Connection(pulse_bus_address())
pulse_core = pulse_bus.get_object(object_path='/org/pulseaudio/core1')
#pulse_clients = pulse_bus.get_object(object_path='/org/pulseaudio/core1/Clients')
#print dir(pulse_clients)
pulse_core.ListenForSignal('org.PulseAudio.Core1.Device.StateUpdated', dbus.Array(signature='o'), dbus_interface='org.PulseAudio.Core1')

pulse_bus.add_signal_receiver(sig_handler, 'StateUpdated')
loop.run()

关于python - 让信号在 PulseAudio 的 DBus 接口(interface)上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250864/

相关文章:

windows - QtService 应用程序作为服务运行时无法连接到系统总线

Java 音频无法在 Linux 中播放 wav 文件

Docker 安装/tmp/pulseaudio 给出错误

gstreamer - 存储 AAC 音频和检索

python - 主循环,事件循环在DBus服务中的作用

c++ - 使用系统 DBus 的 registerService 失败(但适用于 session DBus)

python - 如何在 Django App 中使用 Bower 包管理器?

python - python中有getch()模拟吗?

python - 删除模块以清理命名空间?

python - 类似于 zip() 的内置函数,用 None 值从左边填充不等长度