I2S Standard Play Sound
Posted: Thu Aug 03, 2023 4:23 am
Hi, I am trying to play a wav file in ESP32-C3 to I2S DAC.
Here is my init code
I am trying to play the audio using following code
I can't get this working? Please tell me where I am going wrong.
Here is my init code
Code: Select all
static const char *TAG = "example";
#define BUFF_SIZE 2048
i2s_chan_handle_t tx_handle;
void i2s_init(void)
{
i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER);
ESP_LOGI(TAG, "I2S Channel Config Frame number %lu", chan_cfg.dma_frame_num);
ESP_ERROR_CHECK(i2s_new_channel(&chan_cfg, &tx_handle, NULL));
i2s_std_config_t i2s_cfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(16000),
.slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO),
.gpio_cfg = {
.mclk = I2S_GPIO_UNUSED,
.bclk = GPIO_NUM_3,
.ws = GPIO_NUM_2,
.dout = GPIO_NUM_9,
.din = GPIO_NUM_19,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false,
},
}};
ESP_ERROR_CHECK(i2s_channel_init_std_mode(tx_handle, &i2s_cfg));
}
Code: Select all
void play_wav_file(void)
{
dumb_wav_header_t wave_header;
FILE *f = fopen("/spiffs/payment.wav", "r");
if (f == NULL)
{
ESP_LOGE(TAG, "Failed to open the payment.wav");
}
size_t read;
fread(&wave_header, sizeof(wave_header), 1, f);
ESP_LOGI(TAG, "Number of channels: %u", wave_header.num_channels);
ESP_LOGI(TAG, "Bits per sample: %u", wave_header.bits_per_sample);
ESP_LOGI(TAG, "Sample rate: %lu", wave_header.sample_rate);
ESP_LOGI(TAG, "Data size: %lu", wave_header.data_size);
if (wave_header.bits_per_sample != 16)
{
ESP_LOGE(TAG, "Only 16 bit per sample is supported");
return;
}
if (wave_header.num_channels != 2)
{
ESP_LOGE(TAG, "Only 2 channels are supported");
return;
}
lseek(f, sizeof(dumb_wav_header_t), SEEK_SET);
uint32_t number_of_samples = (8 * wave_header.data_size) / 8;
ESP_LOGI(TAG, "Number of samples: %lu", number_of_samples);
uint32_t size_of_sample = (wave_header.num_channels * wave_header.bits_per_sample) / 8;
ESP_LOGI(TAG, "Sample Size: %lu", size_of_sample);
uint8_t *w_buf = (uint8_t *)calloc(1, BUFF_SIZE);
assert(w_buf);
size_t w_bytes = BUFF_SIZE;
while (1)
{
int read_bytes = fread(&w_buf, sizeof(w_buf), 1, f);
if (read_bytes <= 0)
{
ESP_LOGI(TAG, "No more data to read");
return;
}
i2s_channel_write(tx_handle, w_buf, BUFF_SIZE, &w_bytes, 1000);
}
}