在采样频率高于20kSps的情况下,使用外部DAC播放ESP32 I2S音频时出现失真



硬件:ESP32 DevKitV1、PCM5102转接板、SD卡适配器
软件:Arduino框架。

一段时间以来,我一直在努力使用ESP32外部的I2S DAC进行音频播放。问题是我只能在没有失真的情况下播放低采样频率,即低于20kSps。我一直在研究文件,https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/i2s.html,和许多其他来源,但sill还没有设法解决这个问题。

I2S配置功能:

esp_err_t I2Smixer::i2sConfig(int bclkPin, int lrckPin, int dinPin, int sample_rate)
{
// i2s configuration: Tx to ext DAC, 2's complement 16-bit PCM, mono,
const i2s_config_t i2s_config = {
.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX | I2S_CHANNEL_MONO), // only tx, external DAC
.sample_rate = sample_rate,
.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
.channel_format = I2S_CHANNEL_FMT_ONLY_RIGHT, // single channel
// .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, //2-channels
.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL3, // highest interrupt priority that can be handeled in c
.dma_buf_count = 128, //16,
.dma_buf_len = 128, // 64
.use_apll = false,
.tx_desc_auto_clear = true};
const i2s_pin_config_t pin_config = {
.bck_io_num = bclkPin,           //this is BCK pin
.ws_io_num = lrckPin,            // this is LRCK pin
.data_out_num = dinPin,          // this is DATA output pin
.data_in_num = I2S_PIN_NO_CHANGE // Not used
};
esp_err_t ret1 = i2s_driver_install((i2s_port_t)i2s_num, &i2s_config, 0, NULL);
esp_err_t ret2 = i2s_set_pin((i2s_port_t)i2s_num, &pin_config);
esp_err_t ret3 = i2s_set_sample_rates((i2s_port_t)i2s_num, sample_rate);
// i2s_adc_disable((i2s_port_t)i2s_num);
// esp_err_t ret3 =  rtc_clk_apll_enable(1, 15, 8, 5, 6);
return ret1 + ret2 + ret3;
}

打开一个以44.1kHz格式的16位单声道PCM创建的波形文件:

File sample_file = SD.open("/test.wav")

在主环路中,样本被馈送到I2S驱动器。

esp_err_t I2Smixer::loop()
{
esp_err_t ret1 = ESP_OK, ret2 = ESP_OK;
int32_t output = 0;
if (sample_file.available())
{
if (sample_file.size() - sample_file.position() > 2) // bytes left
{
int16_t tmp; // 16 bits signed PCM assumed
sample_file.read((uint8_t *)&tmp, 2);
output =(int32_t)tmp;
}
else
{
sample_file.close(); 
}
}
size_t i2s_bytes_write;
int16_t int16_t_output = (int16_t)output;
ret1 = i2s_write((i2s_port_t)i2s_num, &int16_t_output, 2, &i2s_bytes_write, portMAX_DELAY);
if (i2s_bytes_write != 2)
ret2 = ESP_FAIL;
return ret1 + ret2;
}

这适用于高达20kSps的采样率。对于32k或44.1k的采样率,会出现严重失真。我怀疑这是由I2S DMA Tx缓冲区引起的。如果DMA缓冲区的数量(DMA_buf_count(和缓冲区长度(DMA_buf_len(增加,则声音首先播放良好。随后,在短时间之后,失真再次出现。我无法测量这么短的时间跨度,可能在一秒钟左右,但我确实注意到这取决于dma_buf_count和dma_buf_len。

接下来,我尝试将CPU频率提高到240MHz,但没有任何改进。此外,我尝试播放SPIFSS的文件,但没有任何改进。

我现在没有想法,有人也遇到过这个问题吗?

一次读取一个样本并将其推送到I2S驱动程序将不是最有效的驱动程序用法。您在每128字节的DMA缓冲区中只使用了2个字节。这只剩下一个采样周期来在DMA缓冲区"不足"之前推送下一个采样。

以128字节(64个样本(的块读取文件,并将整个块写入I2S,以便有效地使用DMA。

根据文件系统的实现方式,使用与文件系统的介质、扇区大小和DMA缓冲相适应的较大块可能也会更有效率。

最新更新