[C++]我想从wav文件中获取PCM数据
[C++]I want to get PCM data from wav file
我知道 Wave 文件的结构。但是我不知道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;
}
}
上面的代码是我到目前为止所做的。此外,此代码可以准确读取 header。但不知道这样能不能准确读取PCM数据部分。有没有PCM数据结构的参考?我没找到。
"music.wav" 每个样本有 16 位,16 字节速率,立体声通道和两个 blockAlign。以上应该怎么改?
如 this description of wav specifications 中所示,PCM 数据使用小端字节顺序和二进制补码存储,分辨率大于每个样本 8 位。换句话说,在 Intel 处理器上,16 位样本通常对应于 signed short
。此外,对于立体声通道,数据是交错的(left/right 个样本)。
考虑到这一点,假设 "music.wav" 确实包含 16 位 PCM 样本,并且您正在使用 sizeof(short)==2
的编译器在小端平台上读取数据,那么您的代码发布应该正确阅读示例。
我知道 Wave 文件的结构。但是我不知道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;
}
}
上面的代码是我到目前为止所做的。此外,此代码可以准确读取 header。但不知道这样能不能准确读取PCM数据部分。有没有PCM数据结构的参考?我没找到。
"music.wav" 每个样本有 16 位,16 字节速率,立体声通道和两个 blockAlign。以上应该怎么改?
如 this description of wav specifications 中所示,PCM 数据使用小端字节顺序和二进制补码存储,分辨率大于每个样本 8 位。换句话说,在 Intel 处理器上,16 位样本通常对应于 signed short
。此外,对于立体声通道,数据是交错的(left/right 个样本)。
考虑到这一点,假设 "music.wav" 确实包含 16 位 PCM 样本,并且您正在使用 sizeof(short)==2
的编译器在小端平台上读取数据,那么您的代码发布应该正确阅读示例。