36 The Audio Player Class
Phil Schatzmann edited this page 2024-01-30 10:06:10 +01:00

It is pretty simple to build a simple audio player with the help of the Stream API. E.g. a SD file is a subclass of an Arduino Stream, so all you need to do is to copy from the file stream to the desired output stream. Finally you need to add some logic which handles the end of file to automatically process the next file and maybe a status flag to halt and continue the processing. In addition it adds only a little bit of additional complexity to add volume control and meta data support.

In order to simplify things, I decided to provide this functionality as well and to prove the point: The initial version of the AudioPlayer class took only 120 lines of code to implement!

The AudioPlayer supports

  • multiple audio data sources (AudioSourceURL, AudioSourceCallback, File based sources (see below))
  • different Output Scenarios (I2S, PWM, A2DP etc). Just pass the desired output stream object to the constructor.
  • different Decoders for MP3, AAC, WAV. Just pass the desired decoder object to the constructor.
  • Volume Control (by calling player.setVolume())
  • Stopping and Resuming the processing (by calling player.stop() and player.play())
  • Navigation: You can move to the next file by calling player.next(), previous(), setIndex();
  • Metadata
  • multiple processor architectures

AudioSource

An AudioSource is the abstract API used by the AudioPlayer class to navigate and access the audio stream. You can create your own source or just use one of the existing implementations.

File Based Audio Sources

There are quite a few options to choose from (when using an ESP32).

If you select an index file based implementation, the system creates an index file and navigates using the content of the file. You can delete or reorder the content at your will to build your individual playlist!

For the other platforms (e.g. RP2040) I concentrated to have the SDFAT based implementation working. Please feel free to extend the support of the other implementations to other processors as well and help the project by submitting a pull request.

Precondition for Using File Based Audio Sources

Before using this functionality, make sure that your SD or file implementation is working properly! You can find plenty of resources on the internet to learn how to create, open and read files...

Other Sources

Examples

Here are a couple of examples that demonstrate how to use the AudioPlayer class: