如何打开蓝牙连接并成为A2DP源和接收器

时间:2017-06-20 13:46:46

标签: python linux audio bluetooth a2dp

我想使用Python连接到蓝牙设备并将其用作扬声器。例如,使用Python播放.wav并在设备上听到并验证它正在播放等。我想在我的linux盒子上播放音频并在蓝牙设备上收听它。

我正在做一些关于stackoverflow的看法,似乎我可以使用pybluez进行连接,但是后来需要使用dbus来设置实际的音频连接。我找到Linux BlueZ dbus communication a2dp,但结果是:

dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownMethod: Method "DefaultAdapter" with signature "" on interface "org.bluez.Manager" doesn't exist

当它试图从界面上获取默认适配器时,我甚至没有得到原始海报问题。感谢您的任何帮助! 这是代码:

import dbus as dbus
bus = dbus.SystemBus()

man = bus.get_object('org.bluez', '/')
iface = dbus.Interface(man, 'org.bluez.Manager')
adapterPath = iface.DefaultAdapter()
adapter = dbus.Interface(bus.get_object('org.bluez', adapterPath),dbus_interface='org.bluez.Adapter')
devices = adapter.GetProperties()['Devices']

for d in devices:
    dev = dbus.Interface(bus.get_object('org.bluez', d),dbus_interface='org.bluez.Device')
    props = dev.GetProperties()
    if any(AudioSourceServiceClass_UUID in UUID.upper() for UUID in props["UUIDs"]):
        devobj = bus.get_object('org.bluez', d)
        devobj.Trusted = True
        if props["Connected"] == True:
            print  props["Name"] + " is connected!"
            exit()

for d in devices:
    dev = dbus.Interface(bus.get_object('org.bluez', d),dbus_interface='org.bluez.Device')
    props = dev.GetProperties()
    if any(AudioSourceServiceClass_UUID in UUID.upper() for UUID in props["UUIDs"]):
        #This device is an A2DP Audio source
        print  props["Name"] + " has A2DP audio source"
        #dev.connect_to_signal("PropertyChanged", handler_for_device(dev))
        #dev.connect_to_signal("PropertyChanged", cb)
        devobj = bus.get_object('org.bluez', d)
        try:
            devobj.Connect(dbus_interface='org.bluez.AudioSource')
            devobj.Play()
            exit()
        except dbus.DBusException, e:
            print str(e)

我有两个问题。

  1. 如何成为A2DP来源?
  2. 如何修复获取适配器路径时抛出的异常?

1 个答案:

答案 0 :(得分:1)

此代码不起作用的原因是bluez 5.0不再支持org.bluez.Manager类。

在这里有模糊的描述:http://www.bluez.org/bluez-5-api-introduction-and-porting-guide/

bluez源代码中有一些示例,例如:这里的test / list-devices:https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/test/list-devices

这是该代码的python3版本:

const b = [4, [3,1],1,[[2], 1]]; // 4*1 + 3*2 + 1*2 + 2*3 + 1*2 + 1*1

function addNormalize(arr, sum=0, depth=1) {
    for(let i=0; i< arr.length; i++) {
        const cur = arr[i];
        if (Array.isArray(cur)) {
            depth+=1;
            addNormalize(cur, sum);
        } else {
            sum+=cur * depth;
        }
    }
    return sum;
}

console.log(addNormalize(b))