In my Arduino ESP32-A2DP library I am providing some very simple examples that show how to transform the ESP32 into a A2DP source and transmit sound to a Bluetooth Sink (e.g. some Bluetooth Speakers).

I had quite a few questions on how to do this with files, microphones and I2S as input. So I started a small “glue” project which provides some additional audio tools. I plan to provide plenty of additional examples and some more advances scenarios.

In my last blog, I showed how to read audio data from I2S using a digital microphone. In this blog I provide the RAW audio data directly from a file on a SD card! In some future posts, I will demonstrate how to process different file formats.

Streaming from Files on a SD card

The Sketch

Here is the Arduino Sketch that you can use with an I2S audio source:

#include "BluetoothA2DPSource.h"
#include <SPI.h>
#include <SD.h>

BluetoothA2DPSource a2dp_source;
File sound_file;
const char* file_name = "/audio.raw";
const int sd_ss_pin = 5;
const int frame_size_bytes = sizeof(int16_t) * 2;

// callback used by A2DP to provide the sound data
int32_t get_sound_data(Channels* data, int32_t len) {
  // the data in the file must be in int16 with 2 channels 
  size_t result_len_bytes = sound_file.read((uint8_t*)data, len * frame_size_bytes );
  // result is in number of frames
  int32_t result_len = result_len_bytes / frame_size_bytes;
  ESP_LOGD("get_sound_data", "%d -> %d",len );
  return result_len;
}

// Arduino Setup
void setup(void) {
  Serial.begin(115200);

  // Setup SD and open file
  SD.begin(sd_ss_pin);
  sound_file = SD.open(file_name, FILE_READ);

  // start the bluetooth
  Serial.println("starting A2DP...");
  a2dp_source.start("MyMusic", get_sound_data);  
}

// Arduino loop - repeated processing 
void loop() {
}

The get_sound_data() callback is quite straight forward: We are directly reading the raw audio file from the SD card. The audio file must be available using 16 bit integers with 2 channels. In the callback we just need to translate between number of frames and bytes!

Audacity might help you to create the right file format: export with the file name audio.raw as RAW signed 16 bit PCM and copy it to the SD card. In my example I was using the file audio.raw.

The Device

sd

The SD module is connected with the help of the SPI bus

Pins

SD ESP32
VCC 5V
GND GND
CS CS GP5
SCK SCK GP18
MOSI MOSI GP23
MISO MISO GP19

Source Code

Both the project and the example can be found on Github.


0 Comments

Leave a Reply

Your email address will not be published.