如何将音频字节转换为样本

时间:2019-04-08 05:36:02

标签: c++ algorithm winapi voice

这是我的结构

/* wave data block header */
typedef struct wavehdr_tag {
    LPSTR       lpData;                 /* pointer to locked data buffer */
    DWORD       dwBufferLength;         /* length of data buffer */
    DWORD       dwBytesRecorded;        /* used for input only */
    DWORD_PTR   dwUser;                 /* for client's use */
    DWORD       dwFlags;                /* assorted flags (see defines) */
    DWORD       dwLoops;                /* loop control counter */
    struct wavehdr_tag FAR *lpNext;     /* reserved for driver */
    DWORD_PTR   reserved;               /* reserved for driver */
} WAVEHDR, *PWAVEHDR, NEAR *NPWAVEHDR, FAR *LPWAVEHDR;

我有这个变量WAVEHDR waveHeader;

我从麦克风录制了10秒,并且waveHeader->lpData有我的原始记录数据,而waveHeader->dwBytesRecorded是原始数据的长度 现在,我想计算每秒的音量,以说出哪一秒的音量最大,哪一秒的音量最小。

我知道我应该对绝对值求和并除以样本数

从0到1秒的数据长度,我都使用sum += abs(waveHeader->lpData[i]);进行设置,但是效果不佳

它总是为我每秒提供相同的结果,但是我沉默了几秒钟,却说了一些...

我阅读了我必须添加样本,而不是字节。我应该如何将waveHeader->lpData[i]转换为样本?

//len = length of one secs data (waveHeader->dwBytesRecorded/10)
for (int i=0; i<len; i++)
{
    sum += abs(waveHeader->lpData[i]);
}

1 个答案:

答案 0 :(得分:1)

您已使用WAVEFORMATEX捕获音频,对不对?如果是这样,您可以修改以下例程以满足您的需求:

void ProcessSamples(WAVEHDR* header, WAVEFORMATEX* format)
{
    BYTE* pData = (BYTE*)(header->data);
    DWORD dwNumSamples = header->dwBytesRecorded / format->nBlockAlign;

    // 16-bit stereo, the most common format
    if ((format->wBitsPerSample == 16) && (format->nChannels == 2))
    {
        for (DWORD index = 0; index < dwNumSamples; index++)
        {
            short left = *(short*)pData; pData+=2;
            short right = *(short*)pData; pData+=2;
        }
    }
    else if ((format->wBitsPerSample == 16) && (format->nChannels == 1))
    {
        for (DWORD index = 0; index < dwNumSamples; index++)
        {
            short monoSample = *(short*)pData; pData+=2;
        }
    }
    else if ((format->wBitsPerSample == 8) && (format->nChannels == 2))
    {
        // 8-bit samples are unsigned.
        // "128" is the median silent value
        // normalize to a "signed" value
        for (DWORD index = 0; index < dwNumSamples; index++)
        {
            signed char left = (*(signed char*)pData) - 128; pData += 1;
            signed char right = (*(signed char*)pData) - 128; pData += 1;
        }
    }
    else if ((format->wBitsPerSample == 8) && (format->nChannels == 1))
    {
        for (DWORD index = 0; index < dwNumSamples; index++)
        {
            signed char monosample = (*(signed char*)pData) - 128; pData += 1;
        }
    }
}