How it Works

The theory of operation of the Adafruit MP3 library is simple. After instantiating your Adafruit_MP3 object, call player.begin() from your setup function. This does necessary timer and buffer setup.

#include "Adafruit_MP3.h"
  
Adafruit_MP3 player;

void setup() {
  player.begin();

The library uses a timer set to fire whenever a new sample should be played. For most MP3 files, this is 44.1 kHz. When this timer fires, a user-specified function is called. This function should write the samples to the DAC. This function is specified with

player.setSampleReadyCallback(writeDacs);

Where writeDacs is a function:

void writeDacs(int16_t l, int16_t r){
  /* TODO: map the 16 bit values to the DAC resolution
   * and write to the left and right channel DACs
   */
}

This function is called from an interrupt, so it should be short and sweet. It's getting called 44,100 to 48,000 times per second for most MP3 files.

Another callback needs to be specified with instructions for loading the MP3 data into the players input buffer. This is specified with

player.setBufferCallback(getMoreData);

where getMoreData is a function:

int getMoreData(uint8_t *writeHere, int available){
  /* TODO: write up to 'available' bytes of MP3 data 
   * to the location 'writeHere'. Return the actual number of bytes
   * that were written
   */
}

This function should not take too long (especially if it needs to disable interrupts on the microcontroller) to avoid choppy playback.

Once these two callbacks are specified, the 'tick()' function needs to be called as fast as possible from within your 'loop()' function.

void loop() {
  player.tick();
}

The addition of DMA support would be awesome, we have not done that yet :)

Last updated on 2017-11-09 at 04.30.41 PM Published on 2017-11-09 at 04.34.51 PM