Skip to content

A2DP Source

pschatzmann edited this page Oct 3, 2026 · 2 revisions

This can be used to feed e.g. your Bluetooth Speaker with your audio data.

Sending Data with a Callback

We can also generate sound and send it e.g. to a Bluetooth Speaker.

The API is using PCM data normally formatted as 44.1kHz sampling rate, two-channel 16-bit sample data. By default this is encoded with the SBC codec that is built into ESP-IDF: AAC is supported with Custom Codecs.

When you start the BluetoothA2DPSource, you need to pass the Bluetooth name that you want to connect to and a 'call back function' that provides the sound data:

#include "BluetoothA2DPSource.h"

BluetoothA2DPSource a2dp_source;

// callback 
int32_t get_sound_data(uint8_t *data, int32_t byteCount) {
    // generate your sound data 
    // return the effective length in bytes
    return byteCount;
}

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

void loop() {}

Instead of the set_data_callback callback method you can also use set_data_callback_in_frames which uses frames instead of bytes. In Arduino you can also provide a Stream (e.g a File) as data source or a callback which provides streams.

In the examples you can find an implementation that generates sound with the help of the sin() function.

You can also indicate multiple alternative Bluetooth names. The system just connects to the first one which is available:

void setup() {
  static std::vector<const char*> bt_names = {"MyMusic","RadioPlayer","MusicPlayer"};
  a2dp_source.set_data_callback(get_sound_data);
  a2dp_source.start(bt_names); 
} 

Further Information

Clone this wiki locally