问题描述
ubuntu树莓派4连接蓝牙音箱报错 - KAMINO的博客 (imea.me)
ubuntu树莓派蓝牙音箱无法后台连接 - KAMINO的博客 (imea.me)
根据之前的记录并没有完美解决蓝牙音箱后台连接的问题,还会出现无法播放的问题。
系统为 ubuntu server 22.04。这里介绍使用 pulseaudio 的 system-wide 功能实现蓝牙音箱开机后台连接。
解决方案
首先安装 pulseaudio-module-bluetooth
sudo apt update
sudo apt install -y pulseaudio-module-bluetooth
启动 pulseaudio
systemctl --user start pulseaudio
使用 bluetoothctl 扫描并连接到蓝牙音箱。
使用 bluetoothctl 命令进入蓝牙控制台,执行 scan on 扫描蓝牙,scan off 停止扫描蓝牙,devices 查看所有设备,connect <设备地址> 连接到设备。

提示 Connection successful 说明可以连接成功,但是退出控制台后 pulseaudio 进程会自动关闭,蓝牙音箱也会自动断开。开启 pulseaudio 的 system-wide 功能解决该问题。
禁用普通用户的 pulseaudio 服务。
systemctl --user stop pulseaudio
systemctl --user disable pulseaudio
sudo systemctl --global disable pulseaudio

pulse 用户加入 bluetooth 用户组。
sudo usermod -aG bluetooth pulse

需要播放音频的用户,如 ubuntu 用户、root 用户,加入 pulse-access 用户组。
sudo usermod -aG pulse-access ubuntu
sudo usermod -aG pulse-access root
创建 /etc/pulse/system.pa.d 文件夹。
sudo mkdir /etc/pulse/system.pa.d
创建 /etc/pulse/system.pa.d/bluetooth.pa 文件,内容如下。
### Automatically load driver modules for Bluetooth hardware
.ifexists module-bluetooth-policy.so
load-module module-bluetooth-policy
.endif
.ifexists module-bluetooth-discover.so
load-module module-bluetooth-discover
.endif
创建 /etc/systemd/system/pulseaudio.service 文件,内容如下。
[Unit]
Description=PulseAudio Sound Service
After=hciuart.service
[Service]
Type=notify
ExecStart=/usr/bin/pulseaudio --daemonize=no --exit-idle-time=-1 --disallow-exit=true --system
Restart=always
[Install]
WantedBy=default.target
启动服务并设置为开机自启动。
sudo systemctl enable pulseaudio
sudo systemctl start pulseaudio
这时可以使用 bluetoothctl 连接到蓝牙音箱,退出控制台后将保持连接。
sudo bluetoothctl connect <音箱蓝牙地址>
开机自动连接
开机自动连接到蓝牙音箱,这个自行解决,就开机的时候自动运行 sudo bluetoothctl connect 音箱地址。
我用的是智能音箱,写了个脚本可以通过 API 查看音箱蓝牙状态或打开蓝牙,使用 bluetoothctl 判断是否连接,然后脚本加入 systemd 服务,开机时完成自动打开音箱蓝牙、自动连接音箱、自动重连。
文章评论