You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Raspberry Pi上获取蓝牙耳机按键事件码的技术咨询

解决树莓派SSH环境下捕获蓝牙耳机输入事件并绑定playerctl命令

1. 安装无X环境的事件捕获工具evtest

xev依赖X11图形环境,SSH远程连接下无法使用,evtest是纯命令行的输入设备事件读取工具,完全适配无图形场景:

sudo apt update && sudo apt install evtest

2. 定位蓝牙耳机对应的输入设备

执行命令列出所有系统输入设备,找到蓝牙耳机的控制设备:

sudo evtest

在输出列表中找到类似/dev/input/eventX: Bluetooth Audio/Video Remote Control的条目(X为设备编号),选中对应编号回车进入事件监听模式。此时操作蓝牙耳机的播放/暂停、上下曲等按键,终端会输出事件详情,比如:

Event: time 1699999999.999999, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 1

记录下对应功能的code值(比如164对应播放暂停)。

3. 编写事件绑定脚本

创建bt-keybind.sh脚本,监听指定设备事件,匹配code后执行playerctl命令:

#!/bin/bash
# 替换为你找到的蓝牙耳机设备路径
DEVICE="/dev/input/eventX"

sudo evtest "$DEVICE" | while read -r line; do
    # 播放/暂停按键(匹配KEY_PLAYPAUSE按下事件)
    if [[ "$line" == *"KEY_PLAYPAUSE"*"value 1"* ]]; then
        playerctl play-pause
    # 上一曲按键
    elif [[ "$line" == *"KEY_PREVIOUSSONG"*"value 1"* ]]; then
        playerctl previous
    # 下一曲按键
    elif [[ "$line" == *"KEY_NEXTSONG"*"value 1"* ]]; then
        playerctl next
    fi
done

给脚本添加执行权限:

chmod +x bt-keybind.sh

4. 测试与开机自启

  • 测试脚本:运行./bt-keybind.sh,操作蓝牙耳机按键验证playerctl是否正常响应
  • 开机自启(可选):
    1. 创建systemd服务文件:sudo nano /etc/systemd/system/bt-keybind.service
    2. 写入以下内容(替换脚本路径为实际路径):
    [Unit]
    Description=Bluetooth Headset Key Bindings
    After=bluetooth.target
    
    [Service]
    ExecStart=/home/pi/bt-keybind.sh
    User=pi
    Restart=always
    
    [Install]
    WantedBy=multi-user.target
    
    1. 启用并启动服务:
    sudo systemctl daemon-reload
    sudo systemctl enable bt-keybind.service
    sudo systemctl start bt-keybind.service
    

注意事项

  • 确保已安装playerctl:sudo apt install playerctl
  • 不同蓝牙耳机的按键code可能存在差异,以evtest实际输出为准
  • 若evtest找不到设备,先确认蓝牙耳机已配对并连接到树莓派

内容的提问来源于stack exchange,提问作者Amir Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 14:02:14