C++ 读取 WAV 文件的数据部分
Posted
技术标签:
【中文标题】C++ 读取 WAV 文件的数据部分【英文标题】:C++ Reading the Data part of a WAV file 【发布时间】:2012-11-19 14:12:51 【问题描述】:我计划创建一个程序来可视化 .wav 文件的音频波形。
到目前为止,我已经开始正确阅读上述 wav 文件的标题部分。我使用的代码是这样的:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
using std::string;
using std::fstream;
typedef struct WAV_HEADER
char RIFF[4]; // RIFF Header Magic header
unsigned long ChunkSize; // RIFF Chunk Size
char WAVE[4]; // WAVE Header
char fmt[4]; // FMT header
unsigned long Subchunk1Size; // Size of the fmt chunk
unsigned short AudioFormat; // Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM
unsigned short NumOfChan; // Number of channels 1=Mono 2=Sterio
unsigned long SamplesPerSec; // Sampling Frequency in Hz
unsigned long bytesPerSec; // bytes per second
unsigned short blockAlign; // 2=16-bit mono, 4=16-bit stereo
unsigned short bitsPerSample; // Number of bits per sample
char Subchunk2ID[4]; // "data" string
unsigned long Subchunk2Size; // Sampled data length
wav_hdr;
// Function prototypes
int getFileSize(FILE *inFile);
int main(int argc,char *argv[])
wav_hdr wavHeader;
FILE *wavFile;
int headerSize = sizeof(wav_hdr),filelength = 0;
string answer;
do
string input;
string answer;
const char* filePath;
cout << "Pick wav file from the Windows Media File: ";
cin >> input;
cin.get();
cout << endl;
path = "C:\\Windows\\Media\\" + input + ".wav";
filePath = path.c_str();
wavFile = fopen( filePath , "r" );
if(wavFile == NULL)
printf("Can not able to open wave file\n");
//exit(EXIT_FAILURE);
fread(&wavHeader,headerSize,1,wavFile);
filelength = getFileSize(wavFile);
fclose(wavFile);
cout << "File is :" << filelength << " bytes." << endl;
cout << "RIFF header :" << wavHeader.RIFF[0]
<< wavHeader.RIFF[1]
<< wavHeader.RIFF[2]
<< wavHeader.RIFF[3] << endl;
cout << "WAVE header :" << wavHeader.WAVE[0]
<< wavHeader.WAVE[1]
<< wavHeader.WAVE[2]
<< wavHeader.WAVE[3]
<< endl;
cout << "FMT :" << wavHeader.fmt[0]
<< wavHeader.fmt[1]
<< wavHeader.fmt[2]
<< wavHeader.fmt[3]
<< endl;
cout << "Data size :" << wavHeader.ChunkSize << endl;
// Display the sampling Rate form the header
cout << "Sampling Rate :" << wavHeader.SamplesPerSec << endl;
cout << "Number of bits used :" << wavHeader.bitsPerSample << endl;
cout << "Number of channels :" << wavHeader.NumOfChan << endl;
cout << "Number of bytes per second :" << wavHeader.bytesPerSec << endl;
cout << "Data length :" << wavHeader.Subchunk2Size << endl;
cout << "Audio Format :" << wavHeader.AudioFormat << endl;
// Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM
cout << "Block align :" << wavHeader.blockAlign << endl;
cout << "Data string :" << wavHeader.Subchunk2ID[0]
<< wavHeader.Subchunk2ID[1]
<< wavHeader.Subchunk2ID[2]
<< wavHeader.Subchunk2ID[3]
<< endl;
cout << endl << endl << "Try something else? (y/n)";
cin >> answer;
//cin.get();
cout << endl << endl;
while( answer == "y" );
getchar();
return 0;
// find the file size
int getFileSize(FILE *inFile)
int fileSize = 0;
fseek(inFile,0,SEEK_END);
fileSize=ftell(inFile);
fseek(inFile,0,SEEK_SET);
return fileSize;
我已经尝试了几次,它提供的数据通过 Windows 文件夹中 Media 文件夹中的不同 wav 文件似乎是一致的。
下一步就是将 wav 文件的实际数据存储在向量中。但是,我对如何做到这一点一无所知。我发现的在线解决方案只能读取头文件。
关于如何存储(并希望显示)wav 文件的实际数据的任何想法? 谢谢!
【问题讨论】:
请注意,您应该不使用unsinged long
、short
甚至char
或其他此类类型来读取二进制文件。这些类型的大小和符号可能并不完全符合您的预期(尤其是long
,它可以是 32 位或 64 位,具体取决于平台)。而是使用来自<cstdint>
的类型,例如uint32_t
等。
Similar question for C# 和(一些带有通用标题的具体问题)1 2 3 4
【参考方案1】:
此图取自a Stanford course
因此您可以看到音频数据紧跟在您已读取的标头之后,并且会有Subchunk2Size
字节的音频数据。
这个的伪代码是
ReadRIFF();
ReadFMT();
int32 chunk2Id = Read32(BigEndian);
int32 chunk2Size = Read32(LittleEndian);
for (int i = 0; i < chunk2Size; i++)
audioData[i] = ReadByte();
如果音频是立体声,data
中将有两个音频流。如果音频经过压缩(mp3、aac 等),您必须先对其进行解压缩。
【讨论】:
需要注意的一个非常重要的事情是 fmt 块并不总是相同的长度。它们可以是末尾有额外字节的 WAVEFORMATEX 实例。使用 Subchunk1 size 找出 fmt 部分的实际大小。您还需要注意,数据块不一定遵循 fmt 块。 WAV 文件不仅可以包含 fmt 或数据块,因此最好检查 chunk2 Id 是否为“数据”,如果不是,则跳过它,直到找到数据块。 另一个需要注意的重要事情是 RIFF 是一种可扩展的格式,并且不能保证“DATA”子块紧跟在“FMT”块之后。 tinyurl.com/riff-wav 此外,如果您正在解码 IBM/MS RIFF 格式,所有多字节字都是小端。正如这张图片所声称的,没有一个是大端的。 (事实上,这张图片声称是大端的数字根本不代表数字,字节序只是您希望如何将字节序列解释为数字的问题。) 您的参考链接已失效,因此不清楚您的建议有多规范。我认为在"fmt "
之后期待"data"
子块是危险的【参考方案2】:
我知道这是一篇旧帖子,但是您的 fread 参数已切换,这是一个更正确的版本(需要 g++-4.7 或更高版本,带有 -std=c++11 标志,例如“g++ -std=c++ 11 WaveReader.cpp -o WaveReader")。
#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::string;
typedef struct WAV_HEADER
/* RIFF Chunk Descriptor */
uint8_t RIFF[4]; // RIFF Header Magic header
uint32_t ChunkSize; // RIFF Chunk Size
uint8_t WAVE[4]; // WAVE Header
/* "fmt" sub-chunk */
uint8_t fmt[4]; // FMT header
uint32_t Subchunk1Size; // Size of the fmt chunk
uint16_t AudioFormat; // Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM
uint16_t NumOfChan; // Number of channels 1=Mono 2=Sterio
uint32_t SamplesPerSec; // Sampling Frequency in Hz
uint32_t bytesPerSec; // bytes per second
uint16_t blockAlign; // 2=16-bit mono, 4=16-bit stereo
uint16_t bitsPerSample; // Number of bits per sample
/* "data" sub-chunk */
uint8_t Subchunk2ID[4]; // "data" string
uint32_t Subchunk2Size; // Sampled data length
wav_hdr;
// Function prototypes
int getFileSize(FILE* inFile);
int main(int argc, char* argv[])
wav_hdr wavHeader;
int headerSize = sizeof(wav_hdr), filelength = 0;
const char* filePath;
string input;
if (argc <= 1)
cout << "Input wave file name: ";
cin >> input;
cin.get();
filePath = input.c_str();
else
filePath = argv[1];
cout << "Input wave file name: " << filePath << endl;
FILE* wavFile = fopen(filePath, "r");
if (wavFile == nullptr)
fprintf(stderr, "Unable to open wave file: %s\n", filePath);
return 1;
//Read the header
size_t bytesRead = fread(&wavHeader, 1, headerSize, wavFile);
cout << "Header Read " << bytesRead << " bytes." << endl;
if (bytesRead > 0)
//Read the data
uint16_t bytesPerSample = wavHeader.bitsPerSample / 8; //Number of bytes per sample
uint64_t numSamples = wavHeader.ChunkSize / bytesPerSample; //How many samples are in the wav file?
static const uint16_t BUFFER_SIZE = 4096;
int8_t* buffer = new int8_t[BUFFER_SIZE];
while ((bytesRead = fread(buffer, sizeof buffer[0], BUFFER_SIZE / (sizeof buffer[0]), wavFile)) > 0)
/** DO SOMETHING WITH THE WAVE DATA HERE **/
cout << "Read " << bytesRead << " bytes." << endl;
delete [] buffer;
buffer = nullptr;
filelength = getFileSize(wavFile);
cout << "File is :" << filelength << " bytes." << endl;
cout << "RIFF header :" << wavHeader.RIFF[0] << wavHeader.RIFF[1] << wavHeader.RIFF[2] << wavHeader.RIFF[3] << endl;
cout << "WAVE header :" << wavHeader.WAVE[0] << wavHeader.WAVE[1] << wavHeader.WAVE[2] << wavHeader.WAVE[3] << endl;
cout << "FMT :" << wavHeader.fmt[0] << wavHeader.fmt[1] << wavHeader.fmt[2] << wavHeader.fmt[3] << endl;
cout << "Data size :" << wavHeader.ChunkSize << endl;
// Display the sampling Rate from the header
cout << "Sampling Rate :" << wavHeader.SamplesPerSec << endl;
cout << "Number of bits used :" << wavHeader.bitsPerSample << endl;
cout << "Number of channels :" << wavHeader.NumOfChan << endl;
cout << "Number of bytes per second :" << wavHeader.bytesPerSec << endl;
cout << "Data length :" << wavHeader.Subchunk2Size << endl;
cout << "Audio Format :" << wavHeader.AudioFormat << endl;
// Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM
cout << "Block align :" << wavHeader.blockAlign << endl;
cout << "Data string :" << wavHeader.Subchunk2ID[0] << wavHeader.Subchunk2ID[1] << wavHeader.Subchunk2ID[2] << wavHeader.Subchunk2ID[3] << endl;
fclose(wavFile);
return 0;
// find the file size
int getFileSize(FILE* inFile)
int fileSize = 0;
fseek(inFile, 0, SEEK_END);
fileSize = ftell(inFile);
fseek(inFile, 0, SEEK_SET);
return fileSize;
【讨论】:
这仅适用于某些 WAV 文件。"fmt "
和"data"
子块的唯一保证是"data"
在"fmt "
之后,可能有你必须跳过的块。每个子块在 ID 后都有一个 32 位的长度,因此跳过未知/不受支持的子块很容易。以上是关于C++ 读取 WAV 文件的数据部分的主要内容,如果未能解决你的问题,请参考以下文章