In a very large wav file, I only want to write to a specific section of this file (without resizing the file in any way). This should be possible, since wav stores the audio content in uncompressed format after the header.
Has anybody done this before?
moritzsur:
In a very large wav file, I only want to write to a specific section of this file (without resizing the file in any way). This should be possible, since wav stores the audio content in uncompressed format after the header.
#include <fstream>
#include <cstdint>
void writeWavSection(const char* filename, int64_t sampleStart, int64_t numSamples, const int16_t* data, int channels, int bytesPerSample) {
std::fstream file(filename, std::ios::binary | std::ios::in | std::ios::out);
if (!file) return;
// Seek to the start of the desired audio section (skip 44-byte header)
int64_t byteOffset = 44 + sampleStart * channels * bytesPerSample;
file.seekp(byteOffset, std::ios::beg);
// Write the new audio data
file.write(reinterpret_cast<const char*>(data), numSamples * channels * bytesPerSample);
file.close();
}
int main() {
int16_t newData[] = {1000, 2000, 3000, 4000}; // Example 16-bit samples
writeWavSection("audio.wav", 1000, 2, newData, 2, 2); // Write 2 stereo samples at sample index 1000
return 0;
}
1 Like