I am trying to generate sine wave through I2S (MAX98357A) . It showing sine wave but it is distorted as in the image. Below is my code
#include <Arduino.h>
#include <I2S.h>
#define I2S_SAMPLE_RATE (44100)
#define I2S_SAMPLE_BITS 16
#define PIN_LRC 8
#define PIN_BCLK 7
#define PIN_DOUT 25
int count = 0;
void setup()
{
I2S.setSckPin(PIN_BCLK);
I2S.setFsPin(PIN_LRC);
I2S.setDataPin(PIN_DOUT);
if (!I2S.begin(I2S_PHILIPS_MODE, I2S_SAMPLE_RATE, I2S_SAMPLE_BITS))
{
Serial.println("Failed to initialize I2S!");
while (1)
; // do nothing
}
}
int16_t GenerateSineWave()
{
double rad = 2 * M_PI * 1000 * count++ / I2S_SAMPLE_RATE;
int16_t sineVal = 32767 * sin(rad);
return sineVal;
}
void loop()
{
I2S.write(GenerateSineWave());
I2S.write(GenerateSineWave());
}

It might work better if you "write" more than 2 bytes at a time. Create a larger buffer and write the whole buffer to the driver. Loop up: i2s_driver_install((i2s_port_t)I2S_NUM, &i2s_config, 0, NULL); and how to use it. Then use i2s_write((i2s_port_t)I2S_NUM, buffer, ((bits + 8) / 16) * SAMPLE_PER_CYCLE * 4, &i2s_bytes_write, 100); after filling the buffer. This will keep the DMA channel full and should give a smoother sine wave.