优化这段代码uint8_t *audio_buffer = (uint8_t *)calloc(1, AUDIO_BUFFER_SIZE); assert(audio_buffer); size_t r_bytes = 0; size_t w_bytes = 0; uint8_t volume = 1; FILE *f_read_audio = fopen("/sdcard/wav/bell/CueTone.WAV", "rb"); if (f_read_audio == NULL) { ESP_LOGI(TAG, "Failed to open file"); } else { while (1) { r_bytes = fread(audio_buffer, 1, AUDIO_BUFFER_SIZE, f_read_audio); if (r_bytes == 0) { ESP_LOGI(TAG, "i2s_task will delete"); break; } ESP_LOGI(TAG, ":read %s bytes\n", audio_buffer); // 调整音量大小 int16_t *pcmdata = (int16_t *)audio_buffer; for (int i = 0; i < r_bytes / 2; i++) { int32_t temp = (int32_t)(*pcmdata); temp = temp * volume; temp = temp / 10; *pcmdata = (int16_t)temp; pcmdata++; } // for (int i = 0; i < r_bytes; i += 2) // { // audio_buffer[i] = audio_buffer[i + 1]; // audio_buffer[i + 1] = audio_buffer[i]; // } /* Write i2s data */ if (i2s_channel_write(tx_chan, audio_buffer, AUDIO_BUFFER_SIZE, &w_bytes, portMAX_DELAY) == ESP_OK) { ESP_LOGI(TAG, "Write Task: i2s write %d bytes\n", w_bytes); } else { ESP_LOGI(TAG, "Write Task: i2s write failed\n"); } } }
时间: 2024-02-10 12:07:10 浏览: 112
C实现与 uint64_t 相同功能的类
这段代码需要做以下优化:
1. 避免使用动态内存分配函数 calloc,因为它会频繁调用 malloc 和 free 函数,影响性能,可以使用静态分配的数组代替。
2. 避免在循环中频繁调用 fread 函数,可以将文件读取到缓存中,然后再从缓存中读取数据。
3. 避免在循环中频繁调用 i2s_channel_write 函数,可以将数据写入缓存中,然后再从缓存中写入 i2s 通道。
4. 调整音量大小时可以使用移位运算代替除法运算,提高性能。
下面是优化后的代码:
```c
#define AUDIO_BUFFER_SIZE 2048
uint8_t audio_buffer[AUDIO_BUFFER_SIZE];
size_t r_bytes = 0;
size_t w_bytes = 0;
uint8_t volume = 10;
FILE *f_read_audio = fopen("/sdcard/wav/bell/CueTone.WAV", "rb");
if (f_read_audio == NULL)
{
ESP_LOGI(TAG, "Failed to open file");
}
else
{
// 读取整个文件到缓存中
fseek(f_read_audio, 0, SEEK_END);
size_t file_size = ftell(f_read_audio);
fseek(f_read_audio, 0, SEEK_SET);
size_t read_size = fread(audio_buffer, 1, file_size, f_read_audio);
fclose(f_read_audio);
int16_t *pcmdata = (int16_t *)audio_buffer;
for (int i = 0; i < read_size / 2; i++)
{
int32_t temp = (int32_t)(*pcmdata);
temp = (temp * volume) >> 3; // 移位运算代替除法运算
*pcmdata = (int16_t)temp;
pcmdata++;
}
// 将数据写入 i2s 缓存中
int offset = 0;
while (offset < read_size)
{
size_t write_size = MIN(read_size - offset, AUDIO_BUFFER_SIZE);
memcpy(audio_buffer, audio_buffer + offset, write_size);
if (i2s_channel_write(tx_chan, audio_buffer, write_size, &w_bytes, portMAX_DELAY) == ESP_OK)
{
ESP_LOGI(TAG, "Write Task: i2s write %d bytes\n", w_bytes);
}
else
{
ESP_LOGI(TAG, "Write Task: i2s write failed\n");
}
offset += write_size;
}
}
```
阅读全文