简体   繁体   English

[C ++]我想从wav文件中获取PCM数据

[英][C++]I want to get PCM data from wav file

I know the Wave file's structure. 我知道Wave文件的结构。 But I don't know the exact structure of PCM DATA. 但是我不知道PCM DATA的确切结构。

#include<iostream>
#include<fstream>
using namespace std;

struct WAVE_HEADER{
    char Chunk[4];
    int ChunkSize;
    char format[4];
    char Sub_chunk1ID[4];
    int Sub_chunk1Size;
    short int AudioFormat;
    short int NumChannels;
    int SampleRate;
    int ByteRate;
    short int BlockAlign;
    short int BitsPerSample;
    char Sub_chunk2ID[4];
    int Sub_chunk2Size;
};

struct WAVE_HEADER waveheader;

int main(){
    FILE *sound;
    sound = fopen("music.wav","rb");
    short D;
    fread(&waveheader,sizeof(waveheader),1,sound);
    cout << "BitsPerSample : "  << waveheader.BitsPerSample << endl;
    while(!feof(sound)){
        fread(&D,sizeof(waveheader.BitsPerSample),1,sound);
        cout << int(D) << endl;
    }
}

The above code is what I made so far. 上面的代码是我到目前为止所做的。 Also, this code can read header exactly. 另外,此代码可以准确读取标头。 But I don't know if this can read PCM data part precisely. 但是我不知道这是否可以准确地读取PCM数据。 Is there any reference of PCM data structure? PCM数据结构有参考吗? I couldn't find it. 我找不到

"music.wav" has 16 bits per sample, 16 byte rate, stereo channal and two blockAlign. “ music.wav”每个样本具有16位,16字节速率,立体声声道和两个blockAlign。 How should the above be changed? 以上应如何更改?

As indicated in this description of wav specifications , PCM data are stored using little-endian byte order and two's-complement for resolutions greater than 8 bit per sample. wav规范的说明所示 ,PCM数据使用小尾数字节顺序和二进制补码存储,以使每个样本的分辨率大于8位。 In other words, on an Intel processor, 16-bit samples typically corresponds to signed short . 换句话说,在Intel处理器上,16位样本通常对应于有signed short Additionally, for stereo channels the data is interleaved (left/right samples). 另外,对于立体声声道,数据是交错的(左/右采样)。

With that in mind, assuming "music.wav" does indeed contain 16-bit PCM samples and you are reading the data on a little-endian platform using a compiler where sizeof(short)==2 , then the code you posted should read the samples correctly. 考虑到这一点,假设“ music.wav”的确包含16位PCM样本,并且您正在使用sizeof(short)==2的编译器在Little-endian平台上读取数据,那么您发布的代码应阅读样本正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM