要将 eSpeak 库生成的 PCM 数据转换为 WAV 格式并保存,你可以使用 C++ 的标准文件操作来创建 WAV 文件,并将 PCM 数据写入其中。
#include <iostream>
#include <vector>
#include <cstdint>
#include <cstring>
extern "C" {
#include <speak_lib.h>
}
// WAV 文件头结构
struct WavHeader {
char chunkId[4];
uint32_t chunkSize;
char format[4];
char subchunk1Id[4];
uint32_t subchunk1Size;
uint16_t audioFormat;
uint16_t numChannels;
uint32_t sampleRate;
uint32_t byteRate;
uint16_t blockAlign;
uint16_t bitsPerSample;
char subchunk2Id[4];
uint32_t subchunk2Size;
};
// 将 PCM 数据写入 WAV 文件
void writeWavFile(const std::string& filename, const std::vector<int16_t>& pcmData, uint32_t sampleRate) {
std::ofstream wavFile(filename, std::ios::binary);
if (!wavFile.is_open()) {
std::cerr << "Error opening WAV file for writing!" << std::endl;
return;
}
WavHeader header;
strncpy(header.