A couple of months ago, I described how you can use my Arduino A2DP library to receive music with an ESP32 via Bluetooth e.g. from a mobile phone.

I have extended the library and implemented the BluetoothA2DPSource class that you can use to to the opposite and send sound data from an ESP32 to a Bluetooth Receiver:

#include "BluetoothA2DPSource.h"
#include <math.h> 

BluetoothA2DPSource a2dp_source;

void setup() {
  a2dp_source.start("MyMusic", get_sound_data);  
}

void loop() {
}

That’s pretty easy to use: In the start you just indicate the Bluetooth Device name that you want to connect to and indicate a call back function. So the only challenge is to provide an implementation for the get_sound_data callback method. The supported audio codec in ESP32 A2DP is SBC: SBC audio stream is encoded from PCM data normally formatted as 44.1kHz sampling rate with two-channel 16-bit sample data.

Here is an simple implementation that just generates some sound with the help of the sin() function:

#define c3_frequency  130.81
#define c4_frequency  261.63 

// The supported audio codec in ESP32 A2DP is SBC. SBC audio stream is encoded
// from PCM data normally formatted as 44.1kHz sampling rate, two-channel 16-bit sample data
int32_t get_data(uint8_t *data, int32_t len) {
    if (len < 0 || data == NULL) {
        return 0;
    }
    Channels* ch_data = (Channels*) data;
    static double m_time = 0.0;
    double m_amplitude = 10000;  // max -32,768 to 32,767
    double m_deltaTime = 1.0 / 44100;
    double m_phase = 0.0;
    double double_Pi = PI * 2.0;
    for (int sample = 0; sample < len/4; ++sample) {
        ch_data[sample].channel1 = m_amplitude * sin(double_Pi * c3_frequency * m_time + m_phase);
        ch_data[sample].channel2 = m_amplitude * sin(double_Pi * c4_frequency * m_time + m_phase);
        m_time += m_deltaTime;
    }
    return len;
}

The new version 1.1 of the library is available new on Github.

Categories: Arduino

0 Comments

Leave a Reply

Your email address will not be published.