Start playing WAV files on your STM32 devices by following this detailed guide.
INTRODUCTION
By this time, you should have learned about I2S, how to set I2S on STM32CubeIDE, how to interface an SD card and parse a wav file on an STM32 device. With this, your next step should be how to play a wav file on your STM32. It would be interesting to turn your STM32 device into a full-fledged audio player!
Tools you'll Need
It’s best to get an STM32 part that has I2S (Inter-integrated Sound). I2S is one of the best interfaces for digital audio. Additionally, there are lots of neat audio DACs (Digital-to-Analog Converter) modules out there which has this interface.
Some examples of STM32 devices that has I2S:
- STM32 Black Pill (STM32F406CEU6 or STM32F411CEU6)
- STM32F407VE board (STM32F407VETG)
- STM32F4 Discovery (STM32F407VG)
- and others…
In this example, the STM32F407VE board will be used. However, the process should be the same as in the other board types. This board was chosen because it already has an SD card slot.
An STM32 Programmer/Debugger
A Micro SD Card:
- SanDisk 16GB or other brands and sizes.
You”ll be at an advantage if you’re using STM32 modules that has an SD card slot so you don’t need to wire them up and do additional troubleshooting.
- 2 x MAX98357AÂ modules
- GY‑PCM5102 modules
- and others…
- 2 x speakers (3W at least)
- A mini breadboard
- Connecting wires
Load your SD with a Small PCM WAV File
The WAV file should be stereo in PCM format, preferably with CD quality 44.1 kHz sampling rate and a bit-depth of 16 bits. You can always do audio format conversion in Audacity if you’re having problems with the formats. Name the file with a simple name.
Circuit Setup & Connections
The circuit setup and connections can be seen below. Also, check the STM32CubeIDE Generated report and program attached.
Setup STM32Cube IDE Peripherals
As what’s done in previous projects, open STM32CubeIDE and create a new project using your STM32 IC from your devboard. Add in user LEDs and buttons you may need. Setup debugging and trace for easier troubleshooting using printf.
Setup the Clocks
Enable the oscillator clocks and use the Clock Configuration below as referrence. – STM32F4 devices typically use the PLL48CLK (48 MHz output from the main PLL) to feed peripherals that require precise 48 MHz, such as the USB and SDIO. Similarly, the I2S peripheral needs a precise source coming from the PLLI2S CLK.
Setup SDIO
Set up the SDIO peripheral as below. You can use the previous SD card blog as a reference if you encounter any issues. Remember that if you’re using SDIO in 4-bit mode, you’ll need to modify the SD initialization function to 1-bit mode first.
Setup FATFS
Set up FATFS as below. Do note the parameters and interrupts used. Enable the DMA template as needed. Note also that there is an SD_det pin that detects if the SD Card has been inserted or not. This function is present in the board support package BSP_SD_Init() function.
Setup I2S
Set up the I2S configuration as below. The I2S is set as Half-Duplex Master, 16-bit, Philips, with a CD sampling rate of 44.1 kHz. Enable correct interrupts and DMA settings.
Generate Code
After all is done click save to generate the code.
Start to Code
The whole main.c file can be seen below:
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "fatfs.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdint.h"
#include "stdbool.h"
#include
#include
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
typedef struct {
uint32_t ChunkID; // "RIFF"
uint32_t ChunkSize;
uint32_t Format; // "WAVE"
uint32_t Subchunk1ID; // "fmt "
uint32_t Subchunk1Size; // 16 for PCM
uint16_t AudioFormat; // 1 = PCM
uint16_t NumChannels;
uint32_t SampleRate;
uint32_t ByteRate;
uint16_t BlockAlign;
uint16_t BitsPerSample;
uint32_t Subchunk2ID; // "data"
uint32_t Subchunk2Size; // size of data
} WAV_Header;
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define SAMPLE_RATE 41100.0f // I²S sample rate in Hz
#define AUDIO_BUFFER_SIZE 1024
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
I2S_HandleTypeDef hi2s2;
DMA_HandleTypeDef hdma_spi2_tx;
SD_HandleTypeDef hsd;
DMA_HandleTypeDef hdma_sdio_rx;
DMA_HandleTypeDef hdma_sdio_tx;
/* USER CODE BEGIN PV */
// SD Card variables
FRESULT ret; /* Return value for SD */
FATFS fs; /* File system object for SD logical drive */
FIL fil; /* File object for SD */
UINT bw; /* Number of Bytes Written */
UINT br; /* Number of Bytes Read */
FILINFO file_info; /* File info structure */
// AUDIO variables
uint16_t audioBuffer[AUDIO_BUFFER_SIZE];
WAV_Header header;
uint32_t wavAudioSize = 0;
uint32_t bytesPlayed = 0;; /* Number of Bytes Played */
volatile bool refillHalf = false;
volatile bool refillFull = false;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_SDIO_SD_Init(void);
static void MX_I2S2_Init(void);
/* USER CODE BEGIN PFP */
void AudioTask(void);
void StopPlayback(void);
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_SDIO_SD_Init();
MX_FATFS_Init();
MX_I2S2_Init();
/* USER CODE BEGIN 2 */
// Initialize your Board
uint8_t bsp_r = BSP_SD_Init();
if(bsp_r != 0){
Error_Handler();
}
// Mount the filesystem
ret = f_mount(&fs,"", 1);
if(ret != FR_OK){
Error_Handler();
}
// Open the audio wav file
ret = f_open(&fil, "audio_sampler.wav", FA_READ);
if (ret != FR_OK) {
Error_Handler();
}
// Check file and info
ret = f_stat("audio_sampler.wav", &file_info);
if (ret != FR_OK) {
printf("File not found\n");
Error_Handler();
}else{
printf("File audio_sampler.wav exists, size = %lu bytes\n", file_info.fsize);
}
// Parse the contents of WAV header
if(f_read(&fil, &header, sizeof(WAV_Header), &br) == FR_OK)
{
// Now you can configure I2S/DAC
printf("SampleRate: %lu Hz\n", header.SampleRate);
printf("Channels: %u\n", header.NumChannels);
printf("Bits: %u\n", header.BitsPerSample);
// store audio data size
wavAudioSize = (uint32_t)file_info.fsize - sizeof(WAV_Header);
// Seek to start of PCM data
f_lseek(&SDFile, sizeof(WAV_Header));
// Reset bytes read and bytes played from SD Card
bytesPlayed = 0;
br = 0;
}
else
{
printf("Error reading WAV header\r\n");
Error_Handler();
}
// Read SD PCM data or audio file to audioBuffer
f_read(&fil, audioBuffer, AUDIO_BUFFER_SIZE * sizeof(uint16_t), &br);
// Inc play counter
bytesPlayed = bytesPlayed + (uint32_t)br;
// Then start DMA transfer
HAL_I2S_Transmit_DMA(&hi2s2, audioBuffer, AUDIO_BUFFER_SIZE);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
AudioTask();
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 4;
RCC_OscInitStruct.PLL.PLLN = 168;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief I2S2 Initialization Function
* @param None
* @retval None
*/
static void MX_I2S2_Init(void)
{
/* USER CODE BEGIN I2S2_Init 0 */
/* USER CODE END I2S2_Init 0 */
/* USER CODE BEGIN I2S2_Init 1 */
/* USER CODE END I2S2_Init 1 */
hi2s2.Instance = SPI2;
hi2s2.Init.Mode = I2S_MODE_MASTER_TX;
hi2s2.Init.Standard = I2S_STANDARD_PHILIPS;
hi2s2.Init.DataFormat = I2S_DATAFORMAT_16B;
hi2s2.Init.MCLKOutput = I2S_MCLKOUTPUT_DISABLE;
hi2s2.Init.AudioFreq = I2S_AUDIOFREQ_44K;
hi2s2.Init.CPOL = I2S_CPOL_LOW;
hi2s2.Init.ClockSource = I2S_CLOCK_PLL;
hi2s2.Init.FullDuplexMode = I2S_FULLDUPLEXMODE_DISABLE;
if (HAL_I2S_Init(&hi2s2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN I2S2_Init 2 */
/* USER CODE END I2S2_Init 2 */
}
/**
* @brief SDIO Initialization Function
* @param None
* @retval None
*/
static void MX_SDIO_SD_Init(void)
{
/* USER CODE BEGIN SDIO_Init 0 */
/* USER CODE END SDIO_Init 0 */
/* USER CODE BEGIN SDIO_Init 1 */
/* USER CODE END SDIO_Init 1 */
hsd.Instance = SDIO;
hsd.Init.ClockEdge = SDIO_CLOCK_EDGE_RISING;
hsd.Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE;
hsd.Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE;
hsd.Init.BusWide = SDIO_BUS_WIDE_4B;
hsd.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
hsd.Init.ClockDiv = 10;
/* USER CODE BEGIN SDIO_Init 2 */
// Initially
hsd.Init.BusWide = SDIO_BUS_WIDE_1B;
/* USER CODE END SDIO_Init 2 */
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA2_CLK_ENABLE();
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Stream4_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Stream4_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Stream4_IRQn);
/* DMA2_Stream3_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA2_Stream3_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream3_IRQn);
/* DMA2_Stream6_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA2_Stream6_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream6_IRQn);
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOA, LED1_Pin|LED2_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : BUT_1_Pin BUT_0_Pin */
GPIO_InitStruct.Pin = BUT_1_Pin|BUT_0_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/*Configure GPIO pins : LED1_Pin LED2_Pin */
GPIO_InitStruct.Pin = LED1_Pin|LED2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pin : SD_det_Pin */
GPIO_InitStruct.Pin = SD_det_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
HAL_GPIO_Init(SD_det_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* USER CODE BEGIN 4 */
/**
* Fill part of the buffer with sine wave samples.
* startIndex: where to begin writing
* length: how many samples to write
* phaseOffset: allows continuity between halves
*/
int _write(int file, char *ptr, int len)
{
(void)file;
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
//__io_putchar(*ptr++);
ITM_SendChar(*ptr++);
}
return len;
}
void AudioTask(void) {
if ((refillHalf)&&(bytesPlayed < wavAudioSize)) {
refillHalf = false;
f_read(&fil, &audioBuffer[0], (AUDIO_BUFFER_SIZE/2)*sizeof(uint16_t), &br);
bytesPlayed = bytesPlayed + (uint32_t)br; // inc play ctr
}else{
if ((refillFull)&&(bytesPlayed < wavAudioSize)) {
refillFull = false;
f_read(&fil, &audioBuffer[AUDIO_BUFFER_SIZE/2], (AUDIO_BUFFER_SIZE/2)*sizeof(uint16_t), &br);
bytesPlayed = bytesPlayed + (uint32_t)br; // inc play ctr
}else{
if(bytesPlayed >= wavAudioSize){
StopPlayback();
}
}
}
}
void StopPlayback(void) {
HAL_I2S_DMAStop(&hi2s2);
f_close(&fil);
while(1){ // Finished
HAL_GPIO_TogglePin(LED2_GPIO_Port, LED2_Pin);
HAL_Delay(500);
}
}
/**
* Called when DMA has transmitted HALF of the buffer.
* Refill the first half while the second half is playing.
*/
void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s) {
refillHalf = true;
}
void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s) {
refillFull = true;
}
/**
* Error handler for DMA/I²S issues.
*/
void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s) {
Error_Handler();
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
Includes, type definitions and defines can be seen below. As you can see, a WAV header structure is included to easily access the WAV header components. Note, though, that not all WAV header entries are the same; there are times you need to seek the right data instead of counting each entry. The sample rate is defined, as well as the audio buffer size.
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "fatfs.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdint.h"
#include "stdbool.h"
#include
#include
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
typedef struct {
uint32_t ChunkID; // "RIFF"
uint32_t ChunkSize;
uint32_t Format; // "WAVE"
uint32_t Subchunk1ID; // "fmt "
uint32_t Subchunk1Size; // 16 for PCM
uint16_t AudioFormat; // 1 = PCM
uint16_t NumChannels;
uint32_t SampleRate;
uint32_t ByteRate;
uint16_t BlockAlign;
uint16_t BitsPerSample;
uint32_t Subchunk2ID; // "data"
uint32_t Subchunk2Size; // size of data
} WAV_Header;
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define SAMPLE_RATE 41100.0f // I²S sample rate in Hz
#define AUDIO_BUFFER_SIZE 1024
Below are the global variables used. Note that there is a 16-bit audioBuffer with about 1024 bytes used. The bytesPlayed variable is being monitored to know when to end the WAV player. Two volatile variables, refillHalf and refillFull, are used by the I2S DMA to switch back and forth between half and full DMA memory access and audio buffer memory locations.
/* Private variables ---------------------------------------------------------*/
I2S_HandleTypeDef hi2s2;
DMA_HandleTypeDef hdma_spi2_tx;
SD_HandleTypeDef hsd;
DMA_HandleTypeDef hdma_sdio_rx;
DMA_HandleTypeDef hdma_sdio_tx;
/* USER CODE BEGIN PV */
// SD Card variables
FRESULT ret; /* Return value for SD */
FATFS fs; /* File system object for SD logical drive */
FIL fil; /* File object for SD */
UINT bw; /* Number of Bytes Written */
UINT br; /* Number of Bytes Read */
FILINFO file_info; /* File info structure */
// AUDIO variables
uint16_t audioBuffer[AUDIO_BUFFER_SIZE];
WAV_Header header;
uint32_t wavAudioSize = 0;
uint32_t bytesPlayed = 0;; /* Number of Bytes Played */
volatile bool refillHalf = false;
volatile bool refillFull = false;
There are only two user-defined functions, AudioTask() and StopPlayback(), that run when fetching data from the SD card and streaming that data to the I2S.
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_SDIO_SD_Init(void);
static void MX_I2S2_Init(void);
/* USER CODE BEGIN PFP */
void AudioTask(void);
void StopPlayback(void);
The main function does the usual peripheral initializations. It then proceeds to do the usual SD card functions. Note here that audio_sampler.wav is evaluated by its total file size. After that, the WAV file is parsed to get the sample rate, channel, and bit data. To get the size of the audio data, the total file size is subtracted from the WAV header size. Note that the WAV file entry Subchunk2Size was not used, as it did not contain accurate data; it seems the WAV file header entries for this file are not standard.
To start playing the sound, the SD card is read, and the audio buffer is filled with the initial values. After which, I2S transmission occurs using this buffer. The I2S DMA engine then runs.
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_SDIO_SD_Init();
MX_FATFS_Init();
MX_I2S2_Init();
/* USER CODE BEGIN 2 */
// Initialize your Board
uint8_t bsp_r = BSP_SD_Init();
if(bsp_r != 0){
Error_Handler();
}
// Mount the filesystem
ret = f_mount(&fs,"", 1);
if(ret != FR_OK){
Error_Handler();
}
// Open the audio wav file
ret = f_open(&fil, "audio_sampler.wav", FA_READ);
if (ret != FR_OK) {
Error_Handler();
}
// Check file and info
ret = f_stat("audio_sampler.wav", &file_info);
if (ret != FR_OK) {
printf("File not found\n");
Error_Handler();
}else{
printf("File audio_sampler.wav exists, size = %lu bytes\n", file_info.fsize);
}
// Parse the contents of WAV header
if(f_read(&fil, &header, sizeof(WAV_Header), &br) == FR_OK)
{
// Now you can configure I2S/DAC
printf("SampleRate: %lu Hz\n", header.SampleRate);
printf("Channels: %u\n", header.NumChannels);
printf("Bits: %u\n", header.BitsPerSample);
// store audio data size
wavAudioSize = (uint32_t)file_info.fsize - sizeof(WAV_Header);
// Seek to start of PCM data
f_lseek(&SDFile, sizeof(WAV_Header));
// Reset bytes read and bytes played from SD Card
bytesPlayed = 0;
br = 0;
}
else
{
printf("Error reading WAV header\r\n");
Error_Handler();
}
// Read SD PCM data or audio file to audioBuffer
f_read(&fil, audioBuffer, AUDIO_BUFFER_SIZE * sizeof(uint16_t), &br);
// Inc play counter
bytesPlayed = bytesPlayed + (uint32_t)br;
// Then start DMA transfer
HAL_I2S_Transmit_DMA(&hi2s2, audioBuffer, AUDIO_BUFFER_SIZE);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
AudioTask();
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
There is one user function called AudioTask() that is used to refill the audioBuffer with the SD card audio values. Note that this function uses a ping-pong method, where while one-half of the buffer is being filled, the other half can begin audio transmission. This is possible through the full and half I2S DMA callbacks.
After finishing the file, I2S DMA is stopped, and the file in the SD card is closed.
void AudioTask(void) {
if ((refillHalf)&&(bytesPlayed < wavAudioSize)) {
refillHalf = false;
f_read(&fil, &audioBuffer[0], (AUDIO_BUFFER_SIZE/2)*sizeof(uint16_t), &br);
bytesPlayed = bytesPlayed + (uint32_t)br; // inc play ctr
}else{
if ((refillFull)&&(bytesPlayed < wavAudioSize)) {
refillFull = false;
f_read(&fil, &audioBuffer[AUDIO_BUFFER_SIZE/2], (AUDIO_BUFFER_SIZE/2)*sizeof(uint16_t), &br);
bytesPlayed = bytesPlayed + (uint32_t)br; // inc play ctr
}else{
if(bytesPlayed >= wavAudioSize){
StopPlayback();
}
}
}
}
void StopPlayback(void) {
HAL_I2S_DMAStop(&hi2s2);
f_close(&fil);
while(1){ // Finished
HAL_GPIO_TogglePin(LED2_GPIO_Port, LED2_Pin);
HAL_Delay(500);
}
}
/**
* Called when DMA has transmitted HALF of the buffer.
* Refill the first half while the second half is playing.
*/
void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s) {
refillHalf = true;
}
void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s) {
refillFull = true;
}
Download a copy of the firmware here.
STM32 Wav Player in Action
SHOP THIS PROJECT
-
Digital LCD Thermometer Temperature Gauge with Probe
$15.95Original price was: $15.95.$14.95Current price is: $14.95. Add to cart