ESP32 with MAX98357A I2S Digital Amplifier: Playing Audio and Text-To-Speech (Arduino)

In this tutorial, you’ll learn how to use the MAX98357A I2S digital amplifier with the ESP32. We’ll show you how to wire the module to the ESP32 and provide you with some basic examples for audio output. The ESP32 will be programmed using the Arduino IDE.

The MAX98357A is a compact digital class D amplifier. It takes digital audio directly over I2S and drives a speaker without the need for a separate DAC.

ESP32 with MAX98357A I2S Digital Amplifier: Playing Audio and Text-To-Speech

New to the ESP32? Check out our eBook: Learn ESP32 with Arduino IDE (eBook).

Table of Contents

In this tutorial, we’ll cover the following topics:

Introducing the MAX98357A I2S Amplifier

The MAX98357A combines a digital-to-analog converter (DAC) and a Class D amplifier in a single chip. It receives digital audio data through the I2S interface and converts it into an amplified signal that can drive a speaker directly.

ESP32 I2S MAX98357A Amplifier Component Part Pinout

It is a mono amplifier, which means it can only drive one speaker. Even though it receives stereo audio (left and right channels), you can choose to play the left channel, right channel, or both channels mixed together. You can select which option to use by adjusting the voltage or resistance on the SD pin (see the pinout in the next section).

If you want to play stereo sound, you need two MAX98357A and two speakers.

You can also adjust the output gain via the GAIN pin. This refers to how much the amplifier increases the amplitude of the signal.

Where to buy?

You can check our Maker Advisor Tools Page to compare the MAX98357A digital amplifier module price in different stores.

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

MAX98357A Module Pinout

The MAX98357A module comes with pins for power supply (Vin, GND), for the I2S interface (LRC, BCLK, DIN), for gain control (GAIN), and for channel selection and shutdown (SD).

ESP32 I2S MAX98357A Amplifier Component Part Overview
  • LRC/LRCLK (I2S word select): selects left or right I2S channel.
  • BCLK (I2S bit clock): used to synchronize data transmission.
  • DIN: (I2S data) digital audio data input.
  • GAIN: to control the gain setting. You can have a gain of 3dB, 8dB, 9dB, 12dB, or 15dB.
  • SD: used for shutdown mode and for setting which channel is output.
  • GND: Ground
  • VIN: power supply (3.3V to 5V)

You may also like reading: ESP32 with INMP441 I2S Omnidirectional Microphone Module (Arduino IDE).

Setting the Gain

You can set the audio gain via the GAIN pin by connecting it directly to VCC/GND or via a 100KOhm resistor. See the table below:

GainGAIN pin connection
3 dB100 kOhm resistor from GAIN to GND
6 dBVIN
9dB (default)Unconnected
12 dBGND
15 dB100 kOhm resistor from GAIN to VIN

Channel select and shutdown (SD pin)

The SD pin is used for shutdown mode and for setting which channel is output.

SD VoltageMode
Below 0.16V (connected to GND)Shutdown – amp off
0.16V to 0.77V (leave unconnected)Stereo average (L+R)/2
0.77V to 1.4V (a resistor from SD to VIN: 470kOhm at 5V or 330kOhm at 3.3V)Right channel only
Above 1.4V (SD connected to VIN)Left channel only

Connecting the MAX98357A to the ESP32

For our examples, we’ll use the MAX98357A default settings. Wire it to the ESP32 as shown in the following table. You can use any other suitable GPIOs (check the ESP32-S3 DevKit pinout).

ESP32 with I2S MAX98357A Amplifier Circuit

We recommend using an ESP32-S3.

MAX98357AESP32-S3ESP32
LRCGPIO 6GPIO 25
BCLKGPIO 5GPIO 26
DINGPIO 7GPIO 22
GAINLeave unconnectedLeave unconnected
SDLeave unconnectedLeave unconnected
GNDGNDGND
VIN3.3V3.3V

Note: the ESP32S3 doesn’t have default I2S pins. So, you can pick any other suitable GPIOs (avoid strapping pins, PSRAM pins, USB, and input-only pins).

ESP32 with MAX98357A with speaker - wiring diagram fritzing

Then, connect a 4-8Ohm speaker directly to the MAX98357A board’s output terminals.

Speaker for I2S MAX98357A Amplifier

Install ESP32 in Arduino IDE

Before proceeding, make sure you have the Arduino IDE and ESP32 boards add-on installed on your computer. Follow the next tutorial if you haven’t already:

Testing the MAX98357A Amplifier – Output Sound Wave

To test whether the MAX98357A is wired correctly and working as expected, run the following code that outputs a sine wave to produce a tone.

You can upload the code directly to the ESP32. It will work straight away.

/*
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete project details at https://RandomNerdTutorials.com/esp32-max98357a-i2s-digital-amplifier/
*/
#include <driver/i2s.h>
#include <math.h>

// MAX98357 pins
#define MAX_DIN  7
#define MAX_LRC  6
#define MAX_BCLK 5

// Audio parameters
#define SAMPLE_RATE 44100
#define TONE_FREQ   500
#define AMPLITUDE   5000   // Max 32767
#define BUFFER_LEN  256    // frames per buffer

int16_t samples[BUFFER_LEN * 2]; 
float phase = 0.0;                

void generateSineWave() {
  float phaseIncrement = 2.0 * PI * TONE_FREQ / SAMPLE_RATE;

  for (int i = 0; i < BUFFER_LEN; i++) {
    int16_t value = AMPLITUDE * sin(phase);

    samples[2 * i]     = value;   // left
    samples[2 * i + 1] = value;   // right

    phase += phaseIncrement;
    if (phase >= 2.0 * PI) phase -= 2.0 * PI;
  }
}

void setup() {

  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
    .sample_rate = SAMPLE_RATE,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
    .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
    .communication_format = I2S_COMM_FORMAT_I2S,
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 8,
    .dma_buf_len = BUFFER_LEN,
    .use_apll = false,
    .tx_desc_auto_clear = true,
    .fixed_mclk = 0
  };

  i2s_pin_config_t pin_config = {
    .bck_io_num = MAX_BCLK,
    .ws_io_num = MAX_LRC,
    .data_out_num = MAX_DIN,
    .data_in_num = I2S_PIN_NO_CHANGE
  };

  i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);
  i2s_set_pin(I2S_NUM_0, &pin_config);
}

void loop() {
  generateSineWave();

  size_t bytes_written;
  i2s_write(I2S_NUM_0, samples, sizeof(samples), &bytes_written, portMAX_DELAY);
}

View raw code

How Does the Code Work?

Continue reading to learn how the code works, or skip to the demonstration section.

Including Libraries

For this example, we’ll use the ESP-IDF driver/i2s.h to deal with I2S for the audio. We also include the math.h library to create a sine wave.

#include <driver/i2s.h>
#include <math.h>

I2S Pins

Define the pins connected to the MAX98357A amplifier.

// MAX98357 pins
#define MAX_DIN  7
#define MAX_LRC  6
#define MAX_BCLK 5

Audio Parameters

Set the parameters for the audio.

// Audio parameters
#define SAMPLE_RATE 44100
#define TONE_FREQ   500
#define AMPLITUDE   5000   // Max 32767
#define BUFFER_LEN  256    // frames per buffer

Here’s the meaning of each of those parameters:

  • SAMPLE_RATE 44100: samples per second sent to the amplifier, per channel.
  • TONE_FREQ 500: the pitch of the sine wave in Hz (500 cycles per second). You can change this value to generate tones with different pitches.
  • AMPLITUDE 5000: the peak value of the wave, which sets the volume.
  • BUFFER_LEN 256: The number of frames generated per loop. A frame is one sample for each channel (left and right), so the samples array holds 256 * 2 values.
int16_t samples[BUFFER_LEN * 2];

Generate a Sine Wave

The following function generates a sine wave with the definitions we defined earlier.

void generateSineWave() {
  float phaseIncrement = 2.0 * PI * TONE_FREQ / SAMPLE_RATE;

  for (int i = 0; i < BUFFER_LEN; i++) {
    int16_t value = AMPLITUDE * sin(phase);

    samples[2 * i]     = value;   // left
    samples[2 * i + 1] = value;   // right

    phase += phaseIncrement;
    if (phase >= 2.0 * PI) phase -= 2.0 * PI;
  }
}

Configure I2S – Configuration Structures

In the setup(), configure the I2S peripheral. Start by creating a structure of type i2s_config_t called i2s_config with the configurations for I2S. Here, we assign the sampling rate, bits per sample, channel (left or right), and other configuration settings.

  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
    .sample_rate = SAMPLE_RATE,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
    .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
    .communication_format = I2S_COMM_FORMAT_I2S,
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 8,
    .dma_buf_len = BUFFER_LEN,
    .use_apll = false,
    .tx_desc_auto_clear = true,
    .fixed_mclk = 0
  };

Here’s what each configuration means.

ConfigurationValueMeaning
modeI2S_MODE_MASTER | I2S_MODE_TXThe ESP32 generates the clocks (master) and only transmit audion.
sample_rate44100Samples per second sent to the amplifier per channel.
bits_per_sampleI2S_BITS_PER_SAMPLE_16BIT16 bits per sample
channel_formatI2S_CHANNEL_FMT_RIGHT_LEFTThe data holds two channels, interleaved. The MAX98357 is mono, so it mixes or selects one depending on the SD pin value. In our case, it will be mixed.
communication_formatI2S_COMM_FORMAT_I2SStandard I2S protocol
intr_alloc_flagsESP_INTR_FLAG_LEVEL1The interrupt priority the driver uses (level 1, low or medium)
dma_buf_count88 DMA buffers are queued, which gives some slack so playback doesn’t glitch
dma_buf_lenBUFFER_LEN (256*2)The length of each DMA buffer, in frames.
use_apllfalseuses the standard clock source instead of the more precise audio PLL
tx_desc_auto_cleartrueOutputs silence automatically if the DMA runs out of data, instead of repeating old samples
fixed_mclk0No fixed master clock. The MAX98357 doesn’t need one.

You can check other possible configuration values in the ESP-IDF I2S documentation.

Then, create another structure (i2s_pin_config_t) to define the I2S pins we’re using. Setting data_in_num to I2S_PN_NO_CHANGE indicates that we don’t have any input.

i2s_pin_config_t pin_config = {
  .bck_io_num = MAX_BCLK,
  .ws_io_num = MAX_LRC,
  .data_out_num = MAX_DIN,
  .data_in_num = I2S_PIN_NO_CHANGE
};

Finally, you can start I2S by calling the following functions with the configuration structures we created previously.

i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);
i2s_set_pin(I2S_NUM_0, &pin_config);

In the loop(), we generate the sine wave.

generateSineWave();

And send the wave data via I2S to the amplifier.

size_t bytes_written;
i2s_write(I2S_NUM_0, samples, sizeof(samples), &bytes_written, portMAX_DELAY);

Testing the Example

After copying the code to the Arduino IDE, you can upload it to your board. We’re using an ESP32S3 DevKitC, so we select ESP32S3 Dev Module.

Then, you can upload the code to your board.

After uploading, you’ll hear a tone beeeeeeeeeeeeeeeee as shown in the following video.



Text-to-speech with the ESP32 and MAX98357A

One of the best things about adding a MAX88347A amplifier to the ESP32 is that you can add text-to-speech to your projects. To do that, we’ll use the ESP32-audioI2S library. It supports text-to-speech and many other audio functionalities, like playing audio from the microSD card, that you may need for your audio projects.

This library only works on multi-core chips like ESP32-S3, ESP32-S31, or ESP32-P4. PSRAM is required! Due to its lack of performance, the ESP32 has limited applicability for audio.

It does not work on the ESP32-S2, ESP32-C3, etc.

ESP32-audoI2S Library

Install the ESP32-audioI2S library in your Arduino IDE. Open the Library Manager and search for ESP32-audioI2S. Install the library by schreibfaul1.

Install ESP32-audioI2S library in Arduino IDE

ESP32 Text-to-Speech with MAX98357A Amplifier and ESP32-audioI2S Library

The following code is a simple example showing how to transform text to speech with the ESP32 and output it to the MAX98357A amplifier.

The example we’ll test uses Google’s free web TTS endpoint (the one behind Google Translate), so there’s no account, no API key, and no billing. You only need Wi-Fi so the ESP32 can reach the internet.

The code is based on this example provided by the library. You can find all examples in its GitHub examples folder. The library provides other examples that you can check them here.

/*
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete project details at https://RandomNerdTutorials.com/esp32-max98357a-i2s-digital-amplifier/
*/
#include "Arduino.h"
#include "Audio.h"
#include "WiFi.h"

// MAX98357 pins
#define MAX_DIN  7
#define MAX_LRC  6
#define MAX_BCLK 5

Audio audio;

// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Callback function for debugging
void my_audio_info(Audio::msg_t m) {
    Serial.printf("%s: %s\n", m.s, m.msg);
}

void setup() {
    Serial.begin(115200);

    Audio::audio_info_callback = my_audio_info;
    // Start the Wi-Fi connection
    WiFi.begin(ssid, password);
    Serial.print("Connecting to Wi-Fi");
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("\nWi-Fi Connected!");
    
    audio.setPinout(MAX_BCLK, MAX_LRC, MAX_DIN);
    audio.setVolume(16); // default 0...21
    audio.connecttospeech("Hello world! Testing the ESP32.", "en"); // Google TTS
}

void loop() {
    audio.loop();
    vTaskDelay(1);
}

View raw code

Insert your SSID and password on the following lines, and the code will work straight away.

// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

How Does the Code Work?

First, import the required libraries.

#include "Arduino.h"
#include "Audio.h"
#include "WiFi.h"

Define the I2S pins you’re using.

// MAX98357 pins
#define MAX_DIN  7
#define MAX_LRC  6
#define MAX_BCLK 5

Create an Audio object called audio that we’ll use to refer to our amplifier.

Audio audio;

Insert your network credentials in the following lines so that the ESP32 can connect to the internet and use Google TTS.

// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

The my_audio_info() is a callback function that will be called by the library in the background whenever it has something to report about the audio processes.

// Callback function for debugging
void my_audio_info(Audio::msg_t m) {
    Serial.printf("%s: %s\n", m.s, m.msg);
}

Then, in the setup(), the following lines set that when there’s a message or error, it should be sent to the my_audio_info() function, which then prints an info or error message to the Serial Monitor.

Audio::audio_info_callback = my_audio_info;

Connect to Wi-Fi using the SSID and password defined earlier.

// Start the Wi-Fi connection
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}
Serial.println("\nWi-Fi Connected!");

Set the pins of the amplifier by using the setPinout() function on the audio object.

audio.setPinout(MAX_BCLK, MAX_LRC, MAX_DIN);

Set the volume using the setVolume() function. You can pass an integer between 0 and 21.

audio.setVolume(10); // default 0...21

Finally, write the message you want to translate to speech. Use the connecttospeech() function. It accepts as arguments the text message and the language. For example, en, de, pt, fr, etc.

audio.connecttospeech("Hello world! Testing the ESP32.", "en"); // Google TTS

Finally, in the loop(), we need to call audio.loop(), which is what actually does the audio work. It continuously processes the audio playback. It handles the background tasks required to play the Google Text-to-Speech audio. The audio.loop() function needs to be called repeatedly so the library can process incoming data and maintain audio playback.

audio.loop();

You cannot use long delays in the loop(). Otherwise, the audio will stutter or stop.

Finally, vTaskDelay(1) briefly yields the CPU (1 RTOS tick), allowing other tasks to run, like connecting to Wi-Fi.

vTaskDelay(1);

Uploading the Code

After inserting your network credentials in the code, you can upload it to your board. Make sure you select an ESP32S3 in Tools > Board.

Then, you also need to select in Tools:

  • Partition Scheme: Huge APP (3MB No OTA/1 MB SPIFFS)
  • PSRAM: OPI PSRAM or QSPI PSRAM, depending on your board model*

* check the print on your board chip:

  • N8R2: 8 MB Flash, 2 MB Quad SPI PSRAM.
  • N8R8: 8 MB Flash, 8 MB Octal SPI PSRAM.
  • N16R8: 16 MB Flash, 8 MB Octal SPI PSRAM.
ESP32 Select Partition Scheme and PSRAM

Demonstration

After selecting the right settings, you can upload the code to your board.

Make sure the amplifier is connected properly to the speaker. Open the Serial Monitor to check the debugging messages.

ESP32 with MAX98357A Text to Speech - Serial Monitor

After uploading the code, press the ESP32 RST button. You’ll hear your message on the speaker.


In this example, we ran the command to output audio in the setup(). So, it will only run once. To hear it again, restart the ESP32 by pressing the RST button.

ESP32 with I2S MAX98357A Amplifier Demonstration

Wrapping Up

In this guide, you learned how to interface the I2S MAX98357A amplifier with the ESP32. You also learned how to set up and configure I2S on the ESP32 to output a sine wave.

For something more advanced with audio, it is better to use a library. The ESP32-audioI2S library provides plenty of examples and simple methods and functions that make it really simple to play audio with the ESP32. As you’ve seen in our second example, with just a few lines of code, we can easily perform text-to-speech, which can be quite useful for many ESP32 IoT and AI assistant projects.

We hope you’ve found this guide useful. You may also like taking a look at our guide for the INMP441 I2S Microphone:

To learn more about the ESP32, check out our resources:



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.