自动连接信任的蓝牙扬声器


10

我已遵循以下教程(http://mygeeks014.blogspot.nl/2015/01/audio-streaming-to-bluetooth-speaker.html)将蓝牙扬声器连接到我的Raspberry Pi。一切都会按预期进行,但是当Raspberry重新启动或打开/关闭扬声器时,扬声器不会自动重新连接。现在,我通过Raspbian GUI手动重新连接扬声器,但是我想知道是否有一种简单的解决方案可以通过CLI重新连接扬声器。然后,如果尚未连接扬声器,我将能够编写一个简单的CRON重新连接扬声器。

Answers:


17

这是一个非常详细的说明:

丹3243

这是命令行解决方案:

首先,让我们使用“ bluetoothctl”进行扫描,配对和信任您的设备。为此,请在您的终端的命令行上运行此命令:

bluetoothctl -a

您应该得到一个不同的命令提示符,例如:

[bluetooth]

在您的BT扬声器打开的情况下,键入以下内容:

scan on

稍后,您应该会看到BT设备可用。设备旁边是MAC地址,例如:00:AA:22:BB:33。现在输入:

info <your mac address>

排除大于和小于字符。您正在寻找的是以前与BT演讲者的某种联系。您会知道之前存在关联,因为bluetoothctl将显示有关BT设备的信息。其中一些信息将与被配对和信任的设备有关。很好

如果bluetoothctl抱怨没有设备,那么我们现在需要进行设置。为此,请键入:

pair <your mac address>

您应该看到有关设备成功配对的成功消息。现在,让我们信任我们的新BT设备。输入:

trust <your mac address>

同样,您应该看到有关信任的成功消息。让我预先警告你。您的BT设备可能会连接,然后又可能无法连接。不用担心,我们不希望它连接。继续,让我们退出“ bluetoothctl”。为此,请键入:

quit

现在,您将回到命令行提示符。在上一篇文章中,我建议您在主目录中创建一个脚本目录。如果还没有,请立即执行。在命令提示符下键入:

mkdir -p ~/scripts

按Enter键,现在我们创建自动配对bash脚本。输入:

nano ~/scripts/autopair

在脚本中输入以下代码:

#!/bin/bash
bluetoothctl << EOF
connect [enter your MAC add]
EOF

排除括号!

现在,同时按CTRL + x,然后按Enter保存脚本。我们需要使其可执行。为此,请键入:

chmod +x ~/scripts/autopair

我假设您不将外部模拟扬声器插入3.5毫米插孔。如果是这样,我们禁用alsa。为此,我们在/ boot目录中编辑一个名为config.txt的文件。为此,请在终端中输入以下内容:

sudo nano /boot/config.txt

向下翻页至文件底部,然后查找两行内容:

# Enable audio (loads snd_bcm2835)
dtparam=audio=on

在显示以下内容的行的前面放置一个(井号#):

dtparam=audio=on

看起来像:

#dtparam=audio=on

按CTRL + x,然后按Enter保存文件。

我假设您已经安装了pulseaudio?如果没有,请继续并从命令行运行以下命令:

sudo apt-get update && sudo apt-get install pulseaudio -y

这将使您成为使蓝牙工作非常重要的组成部分!现在,让我们在主目录中编辑.bashrc文件。输入:

nano ~/.bashrc

向下滚动到底部并添加以下行:

pulseaudio --start

按CTRL + x,然后按Enter保存文件。

好!我们需要进入Python世界。我已经编写了一个Python程序,它将监视蓝牙设备。简而言之,一旦您打开蓝牙扬声器,它将激活RPi与您的蓝牙扬声器之间的连接。反之亦然。让我们在主目录中创建一个名为python的目录。为此,请键入以下命令:

mkdir -p ~/python

现在让我们创建python程序文件。为此,请键入:

nano ~/python/on.py

在该文件中,我们需要复制并粘贴以下内容:

#!/usr/bin/python
#
# Monitor removal of bluetooth reciever
import os
import sys
import subprocess
import time

def blue_it():
    status = subprocess.call('ls /dev/input/event0 2>/dev/null', shell=True)
    while status == 0:
        print("Bluetooth UP")
        print(status)
        time.sleep(15)
        status = subprocess.call('ls /dev/input/event0 2>/dev/null', shell=True)
    else:
        waiting()

def waiting():
    subprocess.call('killall -9 pulseaudio', shell=True)
    time.sleep(3)
    subprocess.call('pulseaudio --start', shell=True)
    time.sleep(2)
    status = subprocess.call('ls /dev/input/event0 2>/dev/null', shell=True)  
    while status == 2:
        print("Bluetooth DOWN")
        print(status)
        subprocess.call('~/scripts/autopair', shell=True)
        time.sleep(15)
        status = subprocess.call('ls /dev/input/event0 2>/dev/null', shell=True)
    else:
        blue_it() 

blue_it()

现在按CTRL + x,然后按Enter保存Python程序文件。现在我们需要使该文件可执行。为此,请键入:

chmod +x ~/python/on.py

最后,让我们将其添加到主目录中的.bashrc脚本中:

nano ~/.bashrc

向下翻页至文件底部,然后添加以下两行:

wait
~/python/on.py

现在按CTRL + x,然后按Enter保存。打开蓝牙扬声器,然后重新启动Raspberry Pi。

祝好运!

-nitrolinux


谢谢你的评论。我还必须按下UI中的“接收音频”按钮,是否还有CLI替代方法?
Den3243 '16

我已经更新了原始答案。
杰森·伍德拉夫

1
感谢您的详细解释!奇迹般有效。
Den3243 '16

我很高兴它成功了!
杰森·伍德拉夫

该脚本最终不会由于blue_it和wait之间的无限递归而最终崩溃吗?
凯文·陈

4

我发现,pulseaudio5当前存在一些问题,尤其是在通过蓝牙播放音频时。因此,我建议不必在调试时调试它们,而只需将PulseAudio6用于所需的内容即可。

我创建了一个可自动执行以下所有操作的存储库,因此您无需进行所有工作,但是如果您仍然愿意进行此操作,请继续执行以下操作。

回购:https : //github.com/BaReinhard/a2dp_bluetooth

安装过程:

git clone https://github.com/bareinhard/a2dp_bluetooth
cd a2dp_bluetooth/a2dp_source
./configure

等待安装过程完成并重新启动。完成后,您将需要初始化,配对,信任和连接设备。初始时间过后,您只需要打开设备。

配对,信任和连接:

sudo bluetoothctl
[bluetooth]# power on
[bluetooth]# agent on
[bluetooth]# default-agent
[bluetooth]# scan on
[bluetooth]# pair XX:XX:XX:XX:XX
[bluetooth]# trust XX:XX:XX:XX:XX
[bluetooth]# connect XX:XX:XX:XX:XX
[bluetooth]# exit

--------------------完整演练:--------------------

编译PulseAudio 6

添加以下文件

/etc/init.d/pulseaudio

#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          pulseaudio esound
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Should-Start:      udev network-manager
# Should-Stop:       udev network-manager
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start the PulseAudio sound server
# Description:       System mode startup script for
#                    the PulseAudio sound server.
### END INIT INFO

DAEMON=/usr/local/bin/pulseaudio
PIDDIR=/var/run/pulse
PIDFILE=$PIDDIR/pid
DAEMONUSER=pulse
PATH=/sbin:/bin:/usr/sbin:/usr/bin

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

pulseaudio_start () {
        log_daemon_msg "Starting system PulseAudio Daemon"
        if [ ! -d $PIDDIR ]; then
                mkdir -p $PIDDIR
                chown $DAEMONUSER:$DAEMONUSER $PIDDIR
        fi
        start-stop-daemon -x $DAEMON -p $PIDFILE --start -- --system --disallow-exit --disallow-module-loading=0 --daemonize --log-target=syslog --high-priority
        status=$?
        if [ -e /var/run/pulse/.esd_auth ]; then
                chown pulse:pulse-access /var/run/pulse/.esd_auth
                chmod 640 /var/run/pulse/.esd_auth
        fi
        if [ -e /var/run/pulse/.pulse-cookie ]; then
                chown pulse:pulse-access /var/run/pulse/.pulse-cookie
                chmod 640 /var/run/pulse/.pulse-cookie
        fi
        log_end_msg ${status}
}

pulseaudio_stop () {
        log_daemon_msg "Stopping system PulseAudio Daemon"
        start-stop-daemon -p $PIDFILE --stop --retry 5 || echo -n "...which is not running"
        log_end_msg $?
}

case "$1" in
        start|stop)
                pulseaudio_${1}
                ;;
        restart|reload|force-reload)
                if [ -s $PIDFILE ] && kill -0 $(cat $PIDFILE) >/dev/null 2>&1; then
                        pulseaudio_stop
                        pulseaudio_start
                fi
                ;;
        force-stop)
                pulseaudio_stop
                killall pulseaudio || true
                sleep 2
                killall -9 pulseaudio || true
                ;;
        status)
                status_of_proc -p $PIDFILE "$DAEMON" "system-wide PulseAudio" && exit 0 || exit $?
                ;;
        *)
                echo "Usage: /etc/init.d/pulseaudio {start|stop|force-stop|restart|reload|force-reload|status}"
                exit 1
                ;;
esac

exit 0

/etc/init.d/bluetooth

#!/bin/sh -e
### BEGIN INIT INFO
# Provides:            bluetooth
# Required-Start:      $local_fs $syslog dbus
# Required-Stop:       $local_fs $syslog
# Default-Start:       2 3 4 5
# Default-Stop:        0 1 6
# Short-Description:   Starts bluetooth daemons
### END INIT INFO

. /lib/lsb/init-functions

DESC=bluetoothd
DAEMON=/usr/libexec/bluetooth/bluetoothd
#SSD_OPTIONS="--oknodo --quiet --exec $DAEMON --plugin=a2dp"
SSD_OPTIONS="--oknodo --quiet --exec $DAEMON" #Change to this if you want media control using DBus at the expense of volume control 
HCI=hci0

case "${1}" in
    start)
       log_daemon_msg "Starting Bluetooth daemon bluetoothd..."
       start-stop-daemon --start --background $SSD_OPTIONS
       log_progress_msg "${DAEMON}"

       hciconfig $HCI up > /dev/null 2>&1
       log_end_msg 0
       ;;

    stop)
        log_daemon_msg "Stopping Bluetooth daemon bluetoothd..."
        start-stop-daemon --stop $SSD_OPTIONS
        log_progress_msg "${DAEMON}"
        log_end_msg 0
       ;;

    restart)
       ${0} stop
       sleep 1
       ${0} start
       ;;

    status)
        status_of_proc "$DAEMON" "$DESC" && exit 0 || exit $?
       ;;

    *)
         echo "Usage: ${0} {start|stop|restart|status}"
         exit 1
       ;;
esac

exit 0

启用新的init.d服务并使其可执行

sudo chmod +x /etc/init.d/bluetooth
sudo chmod +x /etc/init.d/pulseaudio
sudo update-rc.d bluetooth defaults
sudo update-rc.d pulseaudio defaults

确保我们拥有所有必要的模块

sudo apt-get install bluez pulseaudio-module-bluetooth python-dbus libtool intltool libsndfile-dev libcap-dev libjson0-dev libasound2-dev libavahi-client-dev libbluetooth-dev libglib2.0-dev libsamplerate0-dev libsbc-dev libspeexdsp-dev libssl-dev libtdb-dev libbluetooth-dev intltool autoconf autogen automake build-essential libasound2-dev libflac-dev libogg-dev libtool libvorbis-dev pkg-config python -y

转到主目录并从git源安装json-c(PA6必需)

cd ~
git clone https://github.com/json-c/json-c.git
cd json-c
./configure 
make
sudo make install

转到主目录并从git源安装libsndfile

git clone git://github.com/erikd/libsndfile.git
cd libsndfile
./autogen.sh
./configure --enable-werror
make
sudo make install

确保正在搜索蓝牙(sudo hciconfig hci0 piscan已弃用)

cat << EOT | sudo tee -a /etc/bluetooth/main.conf
[Policy]
AutoEnable=true
EOT

导航到主目录并从git源安装PulseAudio 6

git clone --branch v6.0 https://github.com/pulseaudio/pulseaudio
cd pulseaudio
sudo ./bootstrap.sh
sudo make
sudo make install
sudo ldconfig

确保脉搏在所有必要组中

sudo addgroup --system pulse
sudo adduser --system --ingroup pulse --home /var/run/pulse pulse
sudo addgroup --system pulse-access
sudo adduser pulse audio
sudo adduser root pulse-access
sudo adduser pulse lp

更新/etc/pulse/system.pa/etc/pulse/daemon.conf如下所示:

/etc/pulse/system.pa

#!/usr/bin/pulseaudio -nF
#
# This file is part of PulseAudio.
#
# PulseAudio is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# PulseAudio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with PulseAudio; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.

# This startup script is used only if PulseAudio is started in system
# mode.

### Automatically load driver modules depending on the hardware available
.ifexists module-udev-detect.so
 #load-module module-udev-detect
 load-module module-udev-detect tsched=0
.else
### Use the static hardware detection module (for systems that lack udev/hal support)
load-module module-detect
.endif

### Load several protocols
.ifexists module-esound-protocol-unix.so
load-module module-esound-protocol-unix
.endif
load-module module-native-protocol-unix

### Automatically restore the volume of streams and devices
load-module module-stream-restore
load-module module-device-restore

### Automatically restore the default sink/source when changed by the user
### during runtime
### NOTE: This should be loaded as early as possible so that subsequent modules
### that look up the default sink/source get the right value
load-module module-default-device-restore

### Automatically move streams to the default sink if the sink they are
### connected to dies, similar for sources
load-module module-rescue-streams

### Make sure we always have a sink around, even if it is a null sink.
load-module module-always-sink

### Automatically suspend sinks/sources that become idle for too long
load-module module-suspend-on-idle

### Enable positioned event sounds
load-module module-position-event-sounds

### Automatically load driver modules for Bluetooth hardware
.ifexists module-bluetooth-discover.so
    load-module module-bluetooth-discover
.endif
load-module module-bluetooth-policy
load-module module-switch-on-connect

/etc/pulse/daemon.conf

# This file is part of PulseAudio.
#
# PulseAudio is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# PulseAudio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with PulseAudio; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA.

## Configuration file for the PulseAudio daemon. See pulse-daemon.conf(5) for
## more information. Default values are commented out.  Use either ; or # for
## commenting.

; daemonize = no
; fail = yes
; allow-module-loading = yes
; allow-exit = yes
; use-pid-file = yes
; system-instance = no
; local-server-type = user
; enable-shm = yes
; shm-size-bytes = 0 # setting this 0 will use the system-default, usually 64 MiB
; lock-memory = no
; cpu-limit = no

; high-priority = yes
; nice-level = -15

; realtime-scheduling = yes
; realtime-priority = 5

exit-idle-time = -1
; scache-idle-time = 20

; dl-search-path = (depends on architecture)

; load-default-script-file = yes
; default-script-file = /etc/pulse/default.pa

; log-target = auto
; log-level = notice
; log-meta = no
; log-time = no
; log-backtrace = 0

# resample-method defaults to  speex-float-1 on most architectures,
# speex-fixed-1 on ARM
; resample-method = speex-float-1
resample-method = ffmpeg
enable-remixing = no
enable-lfe-remixing = no

; flat-volumes = yes

; rlimit-fsize = -1
; rlimit-data = -1
; rlimit-stack = -1
; rlimit-core = -1
; rlimit-as = -1
; rlimit-rss = -1
; rlimit-nproc = -1
; rlimit-nofile = 256
; rlimit-memlock = -1
; rlimit-locks = -1
; rlimit-sigpending = -1
; rlimit-msgqueue = -1
; rlimit-nice = 31
; rlimit-rtprio = 9
; rlimit-rttime = 1000000

default-sample-format = s16le
default-sample-rate = 44100
;alternate-sample-rate = 48000
default-sample-channels = 2
; default-channel-map = front-left,front-right

default-fragments = 10
default-fragment-size-msec = 10

; enable-deferred-volume = yes
; deferred-volume-safety-margin-usec = 8000
; deferred-volume-extra-delay-usec = 0

设置udev规则

编辑/etc/udev/rules.d/99-com.rules并添加以下两行:

SUBSYSTEM=="input", GROUP="input", MODE="0660"
KERNEL=="input[0-9]*", RUN+="/usr/local/bin/bluez-udev"

创建 /usr/local/bin/bluez-udev

/ usr / local / bin / bluez-udev

#!/bin/bash
name=$(sed 's/\"//g' <<< $NAME)
#exit if not a BT address
if [[ ! $name =~ ^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$ ]]; then exit 0;  fi

bt_name=`grep Name /var/lib/bluetooth/*/$name/info | awk -F'=' '{print $2}'`

audio_sink=bluez_source.$(sed 's/:/_/g' <<< $name)

action=$(expr "$ACTION" : "\([a-zA-Z]\+\).*")
logger "Action: $action"
if [ "$action" = "add" ]; then
    logger "[$(basename $0)] Bluetooth device is being added [$name] - $bt_name"
    logger "[$(basename $0)] Patching $audio_source into ALSA sink #$audio_sink"
    #hciconfig hci0 noscan
    bluetoothctl << EOT
discoverable off
EOT
    # Grab Card Number
    PACARD=`pactl list cards | grep "Card #" | sed "s/Card #//"`

    # Grab Sink Input if it exists
    audio_source=`pactl pactl list sink-inputs | grep "Sink Input" | sed "s/Sink Input #//"`
    if [ $audio_source = "" ];then
        sleep 5
        audio_source=`pactl pactl list sink-inputs | grep "Sink Input" | sed "s/Sink Input #//"`

    fi
    pactl set-sink-volume $audio_sink 65537
    if [ $audio_source != "" ]; then
        pactl set-source-volume $audio_source 90%
    fi
    pactl set-card-profile $PACARD a2dp_sink


    pactl set-default-sink $audio_sink





    # loop back this source to the default sink
    handle=$(pactl load-module module-loopback source=$audio_source sink=$audio_sink)
    logger "[$(basename $0)] PulseAudio module-loopback returned handle [$handle]"
    logger "$bt_name"


fi

if [ "$action" = "remove" ]; then
    # Grab Sink Input if it exists
    audio_source=`pactl pactl list sink-inputs | grep "Sink Input" | sed "s/Sink Input #//"`
    if [ $audio_source = "" ];then
        sleep 5
        audio_source=`pactl pactl list sink-inputs | grep "Sink Input" | sed "s/Sink Input #//"`

    fi
    pactl set-sink-volume 0 65537
    if [ $audio_source = "" ]; then
#        pactl set-default-sink 0
        pactl set-source-volume $audio_source 90%
    else
        pactl move-sink-input $audio_source 0 
    fi

    logger "[$(basename $0)] Bluetooth device is being removed [$name] - $bt_name"
    #hciconfig hci0 pscan

    bluetoothctl << EOT
discoverable on
EOT

    # remove any loopback modules assigned to this source
    # only required for USB sound cards, which PulseAudio will not automatically remove
    for handle in $(pactl list short modules | grep module-loopback | grep source=$audio_source | cut -f 1); do
        logger "[$(basename $0)] Unloading module-loopback with handle [$handle]"
        pactl unload-module $handle
    done

    sleep 5
    amixer cset numid=3 80%
    amixer cset numid=3 80%
fi

确保bluez-udev是可执行的

sudo chmod +x /usr/local/bin/bluez-udev

摘要

在这里做什么?

  • 为蓝牙和PulseAudio创建init.d服务并启用它们
  • 安装PulseAudio6的依赖项
  • 编译PulseAudio6并将Pulse用户添加到必要的组(大多数操作已经完成)
  • 设置daemon.conf和system.pa以加载适当的模块
  • 创建udev规则,以在每次连接设备时运行bluez-udev。bluez-udev检查该设备是否为蓝牙设备,如果是,它将尝试将当前播放的音频连接到pulseaudio创建的蓝牙设备接收器。蓝牙断开连接后,它将把数据流移回默认接收器,或接收器0。在那里,有了所有连接的蓝牙设备后,bluez-udev规则将自动将播放音乐连接到新接收器。连接的蓝牙设备。当然,如果这看起来令人生畏

1

您是否尝试过制作使用hcitool进行连接的Bash脚本?

#!/bin/bash
sudo hcitool cc [speaker Bluetooth address]


为该文件添加可执行权限,然后将其添加到cron(您可以随时选择)。

当我尝试连接蓝牙键盘时,这对我有用。我不确定它是否适用于扬声器(不确定是否使用其他协议)。希望这可以帮助!


0

发现这个更好

sudo bluetoothctl <<EOF
power on
discoverable on
pairable on
agent NoInputNoOutput
default-agent 
EOF
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.