16.04不能使用蓝牙A2DP耳机,成对但不能连接。里面的日志


15

首先,我尝试了以下两种方法:https : //vilimpoc.org/blog/2016/04/30/ubuntu-16-04-bluetooth-speakers/,PulseAudio无法加载蓝牙模块15.10 / 16.04 / 16.10

当我尝试连接Jaybird X2(在台式机和笔记本电脑,broadcom和intel上都尝试过)时,它会配对,连接两秒钟,然后断开连接。

日志形式syslog(从我的台式机上使用Broadcom BT)

May 31 23:50:54 desktop pulseaudio[6247]: [pulseaudio] socket-server.c: bind(): Address already in use
May 31 23:50:54 desktop pulseaudio[6247]: [pulseaudio] module.c: Failed to load module "module-cli-protocol-unix" (argument: ""): initialization failed.
May 31 23:50:54 desktop pulseaudio[6247]: [pulseaudio] socket-server.c: bind(): Address already in use
May 31 23:50:54 desktop pulseaudio[6247]: [pulseaudio] module.c: Failed to load module "module-cli-protocol-unix" (argument: ""): initialization failed.

其他时间:

a2dp-sink profile connect failed for xxxxxxx Protocol not available

编辑..重要说明:

现在我已经发现,试图连接到其他设备工作正常(Micropod BT和三星AirTrack)的大部分时间,但只要我努力Jaybird X2,它禁用/卸载模块蓝牙发现,我要pactl load-module module-bluetooth-discover为其他两个再次起作用。

现在,这发生在笔记本电脑上:

May 31 17:02:58 vooze-x1 pulseaudio[3534]: [pulseaudio] backend-native.c: connect(): Function not implemented
May 31 17:02:58 vooze-x1 pulseaudio[3534]: [pulseaudio] volume.c: Assertion 'pa_channels_valid(channels)' failed at pulse/volume.c:74, function pa_cvolume_set(). Aborting.
May 31 17:02:58 vooze-x1 bluetoothd[865]: Endpoint unregistered: sender=:1.130 path=/MediaEndpoint/A2DPSource
May 31 17:02:58 vooze-x1 bluetoothd[865]: Endpoint unregistered: sender=:1.130 path=/MediaEndpoint/A2DPSink
May 31 17:03:00 vooze-x1 pulseaudio[3764]: [pulseaudio] main.c: User-configured server at {ddcf951d58914c47b9adca0056c50142}unix:/run/user/1000/pulse/native, which appears to be local. Probing deeper.
May 31 17:03:00 vooze-x1 pulseaudio[3767]: [pulseaudio] pid.c: Stale PID file, overwriting.

我以前曾经能够短暂地将其连接到台式机上,但是A2DP大部分时间都无法正常工作。

两个不同的错误,但相同的问题。到底是怎么回事?

蓝牙在Ubuntu 16.04中刚刚坏了吗?它适用于Windows和我的Android手机。

任何帮助都是极好的!:)我设法以某种方式使其短暂工作,首先工作,然后A2DP无法工作..因此,我怀疑这与A2DP有关。不确定。


在连接之前,您是否已将耳机置于配对模式?在关闭的设备上,按住中心键4秒钟,直到红色/绿色闪烁。在Ubuntu中搜索并连接。参见askubuntu.com/questions/259354/…–
塔卡特

是的,并且配对很好。问题不是配对,而是“正在连接” ..它会连接并说“已连接耳机”,然后在两秒钟后断开连接。
Joakim Koed '16

只是问一下,因为这是未正确配对的设备出现连接但随后失败的症状。可能值得重试(从已知设备中删除设备后)。
塔卡特

Takket:我大概做了20次。硬复位耳机,等等,等等
乔金- Koed

1
感谢您提交错误@RobertIanHawdon。我已将自己标记为受影响。
Joakim Koed

Answers:


12

这是一个已知的错误。尝试rmmod btusb ; modprobe btusb。我不得不做四次。

我已经看到我的联想P50与Intel 8260 wifi /蓝牙。有时蓝牙固件在启动时无法正确加载。其他时候它根本不起作用。


2
蓝牙对16.04的支持已经严重退化。
阿米亚斯

@Amias好吧,我也无法在14.04中使蓝牙正常工作。
jarno

1
适用于运行16.04的Lenovo Y510P。我在〜/ .bashrc中添加了别名:alias headphones='sudo rmmod btusb ; sudo modprobe btusb'
BenB

3

尽管其他蓝牙音频设备运行正常,但Jaybird X2和Bluebuds X遇到了相同的问题。戴着耳机,我得到了这个错误:

Assertion 'pa_channels_valid(channels)' failed at pulse/volume.c:74, function pa_cvolume_set(). Aborting.

脉冲音频崩溃了。解决该问题的方法是从来源安装pulseaudio:

这将覆盖默认的系统安装,但在更新软件包之前将一直有效。为了防止更新,我们可以将pulseaudio包置于保留状态:

sudo apt-mark hold libpulse-dev libpulse0 libpulse-mainloop-glib0 pulseaudio pulseaudio-module-bluetooth pulseaudio-utils libpulsedsp pulseaudio-module-x11

请注意,我安装了pulseaudio 9.0,但不是使它起作用的版本。我尝试使用PPA的pulseaudio 9.0的打包版本,但是它也因相同的错误而崩溃。


你好 那也可以编译所有的格数吗?实际上我昨天才从狡猾降级到6。工作完美。
Joakim Koed '16

编译没有问题。你什么意思?
Andrzej Pronobis '16

如果不是版本,有什么不同?
Daniel Szmulewicz

2

我的Bluedio T + 3耳机出现了这个问题,我认为发生的是连接超时。您需要取消注释; exit-idle-time = 20文件中的行/etc/pulse/daemon.conf通过删除分号(;)。

将值更改为-1

exit-idle-time = -1

之后,请bluetoothctl再次尝试尝试并连接到设备。请参阅此处获取说明:

Arch Wiki:蓝牙耳机


1

确保以下各项:

  • Jaybird X2已配对
  • 它被标记为受信任(通过bluetoothctltrust XX:XX:XX:XXXX:XX:XX:XX您的Jaybird的MAC地址在哪里)或通过blueman-manager
  • 它已打开

按下Jaybird X2的电源按钮一次。这可能会触发与已知设备的自动连接。因此,您可能需要确保其他设备不会在这里造成干扰。从那时起,连接是稳定的,并且在重新启动后也会自动连接。

让我知道这是否也解决了您的问题。当我无意中按下电源按钮时,我还做了很多其他事情,并且几乎放弃了;-)因此,也有可能其他事情之一解决了该问题。(已经在围绕蓝牙,pulseaudio,bluez,pactl加载模块进行搜索和尝试,所以我还有很多其他提示:-D)

更新(再次出现连接问题后)

将Jaybird X2连接到Android手机后,即使从Android手机断开连接后,也无法重新连接到笔记本电脑。尚不知道,这到底是什么问题,但是要恢复连接,我必须执行以下操作:

  1. 从我的Android手机(或任何其他设备)上断开Jaybird X2的连接
  2. 重新启动ubuntu
  3. 重新连接工作并且连接稳定(第一次配对时通常不起作用...此后我还需要重新启动)

我还尝试了其他一些东西,看来至少pulseaudio-module-bluetooth是必需的。另外,至少在我的机器上需要wifi /蓝牙共存配置(请参阅:https : //askubuntu.com/a/645072/558838)。最后但并非最不重要的一点:万一我切换到另一台设备,总是需要重新启动才能恢复连接。

总结一下:通过重新启动步骤,我能够成功重新连接Jaybird X2,并且连接稳定。如果有人知道省略重启步骤的简便方法,请贡献:) /etc/init.d/bluetooth restart不够。

(我尝试过的其他步骤):

我调查了我的历史。我还尝试了以下一种方法,其中一种可能有助于上述解决方案:

  • apt-get install pulseaudio-module-bluetooth (在我的系统上未安装)
  • 日志中提到了有关丢失的内容ofono,因此我也安装了
  • 做了一个 sudo chown -R $USER ~/*
  • 也适用:https : //askubuntu.com/a/691299/558838(但是我恢复了它,因为它没有帮助。但是当我尝试自动连接时,它可能仍然处于活动状态)
  • 确实也清除/安装了pulseaudio,blueman,bluetooth packag

感谢您尝试提供帮助,只是对其进行了测试,一经尝试,它便崩溃了。然后,我尝试了一下:pactl load-module module-bluetooth-discover并再次按下电源,它再次使pulseaudio崩溃了:/
Joakim Koed

我已经尝试过为答案添加其他步骤。如果您需要任何详细信息,请询问。
罗兰

好。今天发现了其他东西:睡觉后,我无法恢复工作。重新启动后仍然可以使用。更糟糕的是:一旦建立了蓝牙连接,我的无线连接就不再起作用。它保持连接状态,但不传输任何内容。我必须进一步调查。
罗兰


我使用以下方法解决了wifi /蓝牙共存问题:askubuntu.com/a/645072/558838 :)再次入睡,并恢复了蓝牙连接...所以我可能必须检查我做了什么,以便它现在可以工作...也许共存错误也是稳定连接的问题?至少听起来比我列出的其他东西更合理:-)你也可以尝试那个吗?
罗兰

1

在GitHub上运行脚本

问题将消失。

#! /usr/bin/env python3.5
"""

Fixing bluetooth stereo headphone/headset problem in ubuntu 16.04 and also debian jessie, with bluez5.

Workaround for bug: https://bugs.launchpad.net/ubuntu/+source/indicator-sound/+bug/1577197
Run it with python3.5 or higher after pairing/connecting the bluetooth stereo headphone.

This will be only fixes the bluez5 problem mentioned above .

Licence: Freeware

See ``python3.5 a2dp.py -h``.

Shorthands:

    $ alias speakers="a2dp.py 10:08:C1:44:AE:BC"
    $ alias headphones="a2dp.py 00:22:37:3D:DA:50"
    $ alias headset="a2dp.py 00:22:37:F8:A0:77 -p hsp"

    $ speakers



Check here for the latest updates: https://gist.github.com/pylover/d68be364adac5f946887b85e6ed6e7ae

Thanks to:

 * https://github.com/DominicWatson, for adding the ``-p/--profile`` argument.
 * https://github.com/IzzySoft, for mentioning wait before connecting again.
 * https://github.com/AmploDev, for v0.4.0

Change Log
----------

- 0.4.1
  * Sorting device list

- 0.4.0
  * Adding ignore_fail argument by @AmploDev.
  * Sending all available streams into selected sink, after successfull connection by @AmploDev.

- 0.3.3
  * Updating default sink before turning to ``off`` profile.

- 0.3.2
  * Waiting a bit: ``-w/--wait`` before connecting again.

- 0.3.0
  * Adding -p / --profile option for using the same script to switch between headset and A2DP audio profiles

- 0.2.5
  * Mentioning [mac] argument.

- 0.2.4
  * Removing duplicated devices in select device list.

- 0.2.3
  * Matching ANSI escape characters. Tested on 16.10 & 16.04

- 0.2.2
  * Some sort of code enhancements.

- 0.2.0
  * Adding `-V/--version`, `-w/--wait` and `-t/--tries` CLI arguments.

- 0.1.1
  * Supporting the `[NEW]` prefix for devices & controllers as advised by @wdullaer
  * Drying the code.

"""

import sys
import re
import asyncio
import subprocess as sb
import argparse


__version__ = '0.4.0'


HEX_DIGIT_PATTERN = '[0-9A-F]'
HEX_BYTE_PATTERN = '%s{2}' % HEX_DIGIT_PATTERN
MAC_ADDRESS_PATTERN = ':'.join((HEX_BYTE_PATTERN, ) * 6)
DEVICE_PATTERN = re.compile('^(?:.*\s)?Device\s(?P<mac>%s)\s(?P<name>.*)' % MAC_ADDRESS_PATTERN)
CONTROLLER_PATTERN = re.compile('^(?:.*\s)?Controller\s(?P<mac>%s)\s(?P<name>.*)' % MAC_ADDRESS_PATTERN)
WAIT_TIME = .75
TRIES = 4
PROFILE = 'a2dp'


_profiles = {
    'a2dp': 'a2dp_sink',
    'hsp': 'headset_head_unit',
    'off': 'off'
}

# CLI Arguments
parser = argparse.ArgumentParser(prog=sys.argv[0])
parser.add_argument('-e', '--echo', action='store_true', default=False,
                    help='If given, the subprocess stdout will be also printed on stdout.')
parser.add_argument('-w', '--wait', default=WAIT_TIME, type=float,
                    help='The seconds to wait for subprocess output, default is: %s' % WAIT_TIME)
parser.add_argument('-t', '--tries', default=TRIES, type=int,
                    help='The number of tries if subprocess is failed. default is: %s' % TRIES)
parser.add_argument('-p', '--profile', default=PROFILE,
                    help='The profile to switch to. available options are: hsp, a2dp. default is: %s' % PROFILE)
parser.add_argument('-V', '--version', action='store_true', help='Show the version.')
parser.add_argument('mac', nargs='?', default=None)


# Exceptions
class SubprocessError(Exception):
    pass


class RetryExceededError(Exception):
    pass


class BluetoothctlProtocol(asyncio.SubprocessProtocol):
    def __init__(self, exit_future, echo=True):
        self.exit_future = exit_future
        self.transport = None
        self.output = None
        self.echo = echo

    def listen_output(self):
        self.output = ''

    def not_listen_output(self):
        self.output = None

    def pipe_data_received(self, fd, raw):
        d = raw.decode()
        if self.echo:
            print(d, end='')

        if self.output is not None:
            self.output += d

    def process_exited(self):
        self.exit_future.set_result(True)

    def connection_made(self, transport):
        self.transport = transport
        print('Connection MADE')

    async def send_command(self, c):
        stdin_transport = self.transport.get_pipe_transport(0)
        # noinspection PyProtectedMember
        stdin_transport._pipe.write(('%s\n' % c).encode())

    async def search_in_output(self, expression, fail_expression=None):
        if self.output is None:
            return None

        for l in self.output.splitlines():
            if fail_expression and re.search(fail_expression, l, re.IGNORECASE):
                raise SubprocessError('Expression "%s" failed with fail pattern: "%s"' % (l, fail_expression))

            if re.search(expression, l, re.IGNORECASE):
                return True

    async def send_and_wait(self, cmd, wait_expression, fail_expression='fail'):
        try:
            self.listen_output()
            await self.send_command(cmd)
            while not await self.search_in_output(wait_expression.lower(), fail_expression=fail_expression):
                await wait()
        finally:
            self.not_listen_output()

    async def disconnect(self, mac):
        print('Disconnecting the device.')
        await self.send_and_wait('disconnect %s' % ':'.join(mac), 'Successful disconnected')

    async def connect(self, mac):
        print('Connecting again.')
        await self.send_and_wait('connect %s' % ':'.join(mac), 'Connection successful')

    async def trust(self, mac):
        await self.send_and_wait('trust %s' % ':'.join(mac), 'trust succeeded')

    async def quit(self):
        await self.send_command('quit')

    async def get_list(self, command, pattern):
        result = set()
        try:
            self.listen_output()
            await self.send_command(command)
            await wait()
            for l in self.output.splitlines():
                m = pattern.match(l)
                if m:
                    result.add(m.groups())
            return sorted(list(result), key=lambda i: i[1])
        finally:
            self.not_listen_output()

    async def list_devices(self):
        return await self.get_list('devices', DEVICE_PATTERN)

    async def list_paired_devices(self):
        return await self.get_list('paired-devices', DEVICE_PATTERN)

    async def list_controllers(self):
        return await self.get_list('list', CONTROLLER_PATTERN)

    async def select_paired_device(self):
        print('Selecting device:')
        devices = await self.list_paired_devices()
        count = len(devices)

        if count < 1:
            raise SubprocessError('There is no connected device.')
        elif count == 1:
            return devices[0]

        for i, d in enumerate(devices):
            print('%d. %s %s' % (i+1, d[0], d[1]))
        print('Select device[1]:')
        selected = input()
        return devices[0 if not selected.strip() else (int(selected) - 1)]


async def wait():
    return await asyncio.sleep(WAIT_TIME)


async def execute_command(cmd, ignore_fail=False):
    p = await asyncio.create_subprocess_shell(cmd, stdout=sb.PIPE, stderr=sb.PIPE)
    stdout, stderr = await p.communicate()
    stdout, stderr = \
        stdout.decode() if stdout is not None else '', \
        stderr.decode() if stderr is not None else ''
    if p.returncode != 0 or stderr.strip() != '':
        message = 'Command: %s failed with status: %s\nstderr: %s' % (cmd, p.returncode, stderr)
        if ignore_fail:
            print('Ignoring: %s' % message)
        else:
            raise SubprocessError(message)
    return stdout


async def execute_find(cmd, pattern, tries=0, fail_safe=False):
    tries = tries or TRIES

    message = 'Cannot find `%s` using `%s`.' % (pattern, cmd)
    retry_message = message + ' Retrying %d more times'
    while True:
        stdout = await execute_command(cmd)
        match = re.search(pattern, stdout)

        if match:
            return match.group()
        elif tries > 0:
            await wait()
            print(retry_message % tries)
            tries -= 1
            continue

        if fail_safe:
            return None

        raise RetryExceededError('Retry times exceeded: %s' % message)


async def find_dev_id(mac, **kw):
    return await execute_find('pactl list cards short', 'bluez_card.%s' % '_'.join(mac), **kw)


async def find_sink(mac, **kw):
    return await execute_find('pacmd list-sinks', 'bluez_sink.%s' % '_'.join(mac), **kw)


async def set_profile(device_id, profile):
    print('Setting the %s profile' % profile)
    try:
        return await execute_command('pactl set-card-profile %s %s' % (device_id, _profiles[profile]))
    except KeyError:
        print('Invalid profile: %s, please select one one of a2dp or hsp.' % profile, file=sys.stderr)
        raise SystemExit(1)


async def set_default_sink(sink):
    print('Updating default sink to %s' % sink)
    return await execute_command('pacmd set-default-sink %s' % sink)


async def move_streams_to_sink(sink):
    streams = await execute_command('pacmd list-sink-inputs | grep "index:"', True)
    for i in streams.split():
        i = ''.join(n for n in i if n.isdigit())
        if i != '':
            print('Moving stream %s to sink' % i)
            await execute_command('pacmd move-sink-input %s %s' % (i, sink))
    return sink


async def main(args):
    global WAIT_TIME, TRIES

    if args.version:
        print(__version__)
        return 0

    mac = args.mac

    # Hacking, Changing the constants!
    WAIT_TIME = args.wait
    TRIES = args.tries

    exit_future = asyncio.Future()
    transport, protocol = await asyncio.get_event_loop().subprocess_exec(
        lambda: BluetoothctlProtocol(exit_future, echo=args.echo), 'bluetoothctl'
    )

    try:

        if mac is None:
            mac, _ = await protocol.select_paired_device()

        mac = mac.split(':' if ':' in mac else '_')
        print('Device MAC: %s' % ':'.join(mac))

        device_id = await find_dev_id(mac, fail_safe=True)
        if device_id is None:
            print('It seems device: %s is not connected yet, trying to connect.' % ':'.join(mac))
            await protocol.trust(mac)
            await protocol.connect(mac)
            device_id = await find_dev_id(mac)

        sink = await find_sink(mac, fail_safe=True)
        if sink is None:
            await set_profile(device_id, args.profile)
            sink = await find_sink(mac)

        print('Device ID: %s' % device_id)
        print('Sink: %s' % sink)

        await set_default_sink(sink)
        await wait()

        await set_profile(device_id, 'off')

        if args.profile is 'a2dp':
            await protocol.disconnect(mac)
            await wait()
            await protocol.connect(mac)

        device_id = await find_dev_id(mac)
        print('Device ID: %s' % device_id)

        await set_profile(device_id, args.profile)
        await set_default_sink(sink)
        await move_streams_to_sink(sink)

    except (SubprocessError, RetryExceededError) as ex:
        print(str(ex), file=sys.stderr)
        return 1
    finally:
        print('Exiting bluetoothctl')
        await protocol.quit()
        await exit_future

        # Close the stdout pipe
        transport.close()

    if args.profile == 'a2dp':
        print('"Enjoy" the HiFi stereo music :)')
    else:
        print('"Enjoy" your headset audio :)')


if __name__ == '__main__':
    sys.exit(asyncio.get_event_loop().run_until_complete(main(parser.parse_args())))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.