ESP32 作为蓝牙音源

前面介绍过 ESP32 作为蓝牙音频接收端(蓝牙音箱),这里介绍它作为蓝牙音频的播放端。

首先需要确定蓝牙接收器的名称,用笔记本电脑连接后,可以再设备管理器中看到,这里我使用的是一款蓝牙耳机,名称是“JABRA TALK”:

Jabra Talk 蓝牙耳机

接下来需要安装 ESP32-A2DP-master 这个库。下面的代码是从这个库的Example 中修改而来,代码如下:

/*
  Streaming of sound data with Bluetooth to an other Bluetooth device.
  We provide the complete sound data as a simple c array which 
  can be prepared e.g. in the following way

  - Open any sound file in Audacity. Make sure that it contains 2 channels
    - Select Tracks -> Resample and select 44100
    - Export -> Export Audio -> Header Raw ; Signed 16 bit PCM
  - Convert to c file e.g. with "xxd -i file_example_WAV_1MG.raw file_example_WAV_1MG.c"
    - add the const qualifier to the array definition. E.g const unsigned char file_example_WAV_1MG_raw[] = {
  
  Copyright (C) 2020 Phil Schatzmann
  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
  This program 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 General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "BluetoothA2DPSource.h"
#include "StarWars30.h"
BluetoothA2DPSource a2dp_source;
//SoundData *data = new TwoChannelSoundData((Channels*)StarWars10_raw,StarWars10_raw_len/4);
SoundData *data = new OneChannelSoundData((int16_t*)StarWars30_raw, StarWars30_raw_len/2);

void setup() {
  Serial.begin(115200);
  Serial.println("Start");
  a2dp_source.start("JABRA TALK");    
}

void loop() {
  if (a2dp_source.isConnected()==true) {
      Serial.println("Connected!");
      if (a2dp_source.hasSoundData()==true) {
          Serial.println("Has sound!");
        }
      else {
          Serial.println("No sound!");
          a2dp_source.writeData(data);   
      }  
    }
    else {
      Serial.println("Not connected!");
    }
  delay(2000);  
}

特别注意,因为代码有音频数据需要特别选择 Huge APP 模式:

选择 Huge APP 模式

测试使用的板子是 ESP-WROOM-32,特点是价格偏移兼容性还不错(同样的我试验了 TinkerNode,播放时有卡顿,似乎后台有人一直占用 Soc):

ESP-WROOM-32 很便宜
蓝牙耳机和 ESP32

测试的视频:

https://www.bilibili.com/video/BV1wa411A7et/

特别注意:连接时需要比较有耐心多次尝试,先将耳机设置为配对模式,然后ESP32上电。从资料来看,这样的搭配似乎有兼容性问题,淘宝上的卖家都不承诺蓝牙音频端能够兼容客户的蓝牙接收端。

========================

2023年5月10日

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注