C++生产静音音频文件

C++生产静音音频文件

  • 引言
  • C++代码

引言

你好!本文章将介绍.wav文件格式和如何生产静音wav音频文件。

C++代码

#include 
#include 
#include 

typedef struct tWAVEFORMATEX {
	unsigned short     wFormatTag;     // 音频格式,WAVE_FORMAT_PCM...
	unsigned short     nChannels;      // 声道数
	unsigned long      nSamplesPerSec; // 采样率,通常11025,8000,22050,44100
	unsigned long      nAvgBytesPerSec;// 每秒数据字节数 (nSamplesPerSec * nChannels * wBitsPerSample) / 8
	unsigned short     nBlockAlign;    // 数据块对齐,(nChannels * wBitsPerSample) / 8
	unsigned short     wBitsPerSample; // 采样位数,多为8或16或32
	unsigned short     cbSize;         // 额外信息的大小,PCM格式会忽略该值
} WAVEFORMATEX;

int main(int argc, char** argv) {
	std::vector<char> data;
	for(int i = 0; i<2646000; i++) {
		data.push_back(0);
	}
	
	std::ofstream file("wave.wav", std::ios_base::binary | std::ios_base::trunc);
	if (file.is_open()) { 

		WAVEFORMATEX format = {1, 1, 22050, 44100, 2, 16, 0};
		int WaveHeaderSize = 36; // RIFF 12个字节, 格式块26个字节
		int WaveFormatSize = 16; // 格式块内容长度
		file.write("RIFF", 4);  // ChunkID 
		// RIFF + 格式块 +数据块长度[8+dwSize]
		int fileLen = (data.size() + WaveHeaderSize);
		file.write((char *)&fileLen, 4); // ChunkSize

		file.write("WAVE", 4); // Format
		file.write("fmt ", 4);  // Subchunk1 ID 
		file.write((char *)&WaveFormatSize, 4);  // Subchunk1 Size
		file.write((char *)&format.wFormatTag, 2); // AudioFormat
		file.write((char *)&format.nChannels, 2); // Num Channels 
		file.write((char *)&format.nSamplesPerSec, 4); // Sample Rate
		file.write((char *)&format.nAvgBytesPerSec, 4); //ByteRate
		file.write((char *)&format.nBlockAlign, 2); // BlockAlign
		file.write((char *)&format.wBitsPerSample, 2); //BitsPerSample
		file.write("data", 4); // Subchunk2 ID 
		int size = data.size();
		file.write((char *)&size, 4); // Subchunk2 ID 
		file.write((char *)data.data(), size); //data
		file.close();
	}
	std::cout<<"wave.wav文件大小:"<<data.size() + 36<<"byte"<<std::endl;
	return 0;
}

你可能感兴趣的:(C++,wave)