esp32s3 idf读取sd卡音频文件通过i2s输出的详细程序
时间: 2023-08-15 07:07:53 浏览: 263
以下是ESP32-S3 IDF读取SD卡音频文件通过I2S输出的详细程序:
```c
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "driver/i2s.h"
#include "driver/sdmmc_host.h"
#include "driver/sdspi_host.h"
#include "esp_vfs_fat.h"
#define I2S_NUM 0 // I2S port number
#define I2S_SAMPLE_RATE 44100 // Sample rate of the audio file
#define I2S_SAMPLE_BITS 16 // Sample size of the audio file
#define I2S_BUF_SIZE 1024 // I2S buffer size
#define I2S_READ_SIZE 512 // Size of each I2S read
#define SD_CS_PIN 15 // Chip select pin for the SD card
void i2s_task(void *pvParameters)
{
FILE *file = fopen("/sdcard/test.wav", "r");
if (file == NULL) {
printf("Failed to open file\n");
vTaskDelete(NULL);
}
// Configure I2S
i2s_config_t i2s_config = {
.mode = I2S_MODE_MASTER | I2S_MODE_TX,
.sample_rate = I2S_SAMPLE_RATE,
.bits_per_sample = I2S_SAMPLE_BITS,
.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
.communication_format = I2S_COMM_FORMAT_I2S,
.dma_buf_count = 4,
.dma_buf_len = I2S_BUF_SIZE,
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1
};
i2s_pin_config_t pin_config = {
.bck_io_num = 26,
.ws_io_num = 25,
.data_out_num = 22,
.data_in_num = I2S_PIN_NO_CHANGE
};
i2s_driver_install(I2S_NUM, &i2s_config, 0, NULL);
i2s_set_pin(I2S_NUM, &pin_config);
i2s_zero_dma_buffer(I2S_NUM);
// Allocate buffer for I2S data
char *i2s_data = malloc(I2S_READ_SIZE);
while (1) {
// Read data from file
int bytes_read = fread(i2s_data, 1, I2S_READ_SIZE, file);
// End of file
if (bytes_read == 0) {
break;
}
// Write data to I2S buffer
i2s_write_bytes(I2S_NUM, i2s_data, bytes_read, portMAX_DELAY);
}
// Cleanup
free(i2s_data);
fclose(file);
i2s_driver_uninstall(I2S_NUM);
vTaskDelete(NULL);
}
void sd_task(void *pvParameters)
{
// Initialize SD card
sdmmc_host_t host = SDSPI_HOST_DEFAULT();
sdspi_slot_config_t slot_config = SDSPI_SLOT_CONFIG_DEFAULT();
slot_config.gpio_miso = 19;
slot_config.gpio_mosi = 23;
slot_config.gpio_sck = 18;
slot_config.gpio_cs = SD_CS_PIN;
esp_vfs_fat_sdmmc_mount_config_t mount_config = {
.format_if_mount_failed = false,
.max_files = 5
};
sdmmc_card_t *card;
esp_err_t ret = esp_vfs_fat_sdspi_mount("/sdcard", &host, &slot_config, &mount_config, &card);
if (ret != ESP_OK) {
printf("Failed to mount SD card\n");
vTaskDelete(NULL);
}
// Start I2S task
xTaskCreate(i2s_task, "i2s_task", 2048, NULL, 5, NULL);
vTaskDelete(NULL);
}
void app_main()
{
// Start SD task
xTaskCreate(sd_task, "sd_task", 2048, NULL, 5, NULL);
}
```
这个程序使用ESP32-S3的I2S和SD卡接口来读取音频文件并输出到I2S。在程序中,我们首先打开SD卡并挂载文件系统,然后启动I2S任务。I2S任务从文件中读取数据并将其写入I2S缓冲区。需要注意的是,I2S的配置和音频文件的格式必须匹配。
在使用此程序之前,请确保已将适当的SD卡和I2S电路连接到ESP32-S3开发板上,并将音频文件命名为“test.wav”并存储在SD卡根目录下。
阅读全文