以下是基于 STM32 的 I2S 单声道音频数据进行 PCM 解码的示例代码:

#include "stm32f4xx.h"

#define SAMPLE_RATE 44100
#define BITS_PER_SAMPLE 16
#define BUFFER_SIZE 2048

uint16_t i2s_rx_buffer[BUFFER_SIZE];
int16_t pcm_buffer[BUFFER_SIZE];
uint32_t pcm_buffer_index = 0;

void I2S2_IRQHandler(void)
{
    if (SPI_I2S_GetITStatus(SPI2, SPI_I2S_IT_RXNE) != RESET)
    {
        i2s_rx_buffer[pcm_buffer_index] = SPI_I2S_ReceiveData(SPI2);
        pcm_buffer_index++;

        if (pcm_buffer_index == BUFFER_SIZE)
        {
            pcm_buffer_index = 0;

            for (int i = 0; i < BUFFER_SIZE; i++)
            {
                pcm_buffer[i] = (int16_t) i2s_rx_buffer[i];
            }
        }
    }
}

int main(void)
{
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);

    GPIO_InitTypeDef GPIO_InitStruct;
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_15;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOB, &GPIO_InitStruct);

    GPIO_PinAFConfig(GPIOB, GPIO_PinSource12, GPIO_AF_SPI2);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource13, GPIO_AF_SPI2);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource15, GPIO_AF_SPI2);

    SPI_I2S_DeInit(SPI2);
    SPI_I2S_InitTypeDef I2S_InitStruct;
    I2S_InitStruct.I2S_AudioFreq = SAMPLE_RATE;
    I2S_InitStruct.I2S_Standard = I2S_Standard_LSB;
    I2S_InitStruct.I2S_DataFormat = I2S_DataFormat_16b;
    I2S_InitStruct.I2S_CPOL = I2S_CPOL_Low;
    I2S_InitStruct.I2S_Mode = I2S_Mode_MasterRx;
    I2S_InitStruct.I2S_MCLKOutput = I2S_MCLKOutput_Disable;
    SPI_I2S_Init(SPI2, &I2S_InitStruct);

    SPI_I2S_ITConfig(SPI2, SPI_I2S_IT_RXNE, ENABLE);
    NVIC_InitTypeDef NVIC_InitStruct;
    NVIC_InitStruct.NVIC_IRQChannel = SPI2_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);

    SPI_I2S_Cmd(SPI2, ENABLE);

    while (1)
    {
        // Do something with the PCM buffer
    }
}

该代码使用 STM32 的 SPI2 作为 I2S 接口,将接收到的单声道音频数据存储在 'i2s_rx_buffer' 中,并在每接收 BUFFER_SIZE 个数据时,将其转换为 PCM 格式存储在 'pcm_buffer' 中。在主循环中,您可以使用 'pcm_buffer' 进行后续处理。请注意,该示例代码仅对 16 位精度的 PCM 数据进行了解码,如果您需要处理其他精度的 PCM 数据,您需要相应地更改代码。


原文地址: https://www.cveoy.top/t/topic/oYqF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录