将此代码更改为Append而不是Overwrite(.Wav)

时间:2014-05-22 12:41:50

标签: c++

正如标题所述,我想帮助更改此代码而不是将缓冲区等写入文件,我希望它附加,所以它第一次创建文件,然后如果文件存在它将追加它。

template <typename T>
void write(std::ofstream& stream, const T& t) {
    stream.write((const char*)&t, sizeof(T));
}

template <typename T>
void writeFormat(std::ofstream& stream) {
    write<short>(stream, 1);
}

template <>
void writeFormat<float>(std::ofstream& stream) {
    write<short>(stream, 3);
}

template <typename SampleType>
void writeWAVData(
    char const* outFile,
    SampleType* buf,
    size_t bufSize,
    int sampleRate,
    short channels)
{
    std::ofstream stream(outFile, std::ios::binary);
    stream.write("RIFF", 4);
    write<int>(stream, 36 + bufSize);
    stream.write("WAVE", 4);
    stream.write("fmt ", 4);
    write<int>(stream, 16);
    writeFormat<SampleType>(stream);                                // Format
    write<short>(stream, channels);                                 // Channels
    write<int>(stream, sampleRate);                                 // Sample Rate
    write<int>(stream, sampleRate * channels * sizeof(SampleType)); // Byterate
    write<short>(stream, channels * sizeof(SampleType));            // Frame size
    write<short>(stream, 8 * sizeof(SampleType));                   // Bits per sample
    stream.write("data", 4);
    stream.write((const char*)&bufSize, 4);
    stream.write((const char*)buf, bufSize);
}

以下是流程的一行代码

writeWAVData("test.wav", mixBuffer.Array(), audioSampleSize, 48000, 1);

1 个答案:

答案 0 :(得分:1)

将打开文件的行更改为

std::ofstream stream(outFile, std::ios::out | std::ios::binary | std::ios::app);

std::ios::app标志代表追加。有关详细信息,请参阅文档here