Write AudioSampleBuffer to the selected start and end sample of a wave audio file

i have a requirement where I have to read selected time range from wave audio file into AudioSampleBuffer, modify AudioSampleBuffer and write to same location in the audio file is it possible in juce. all the examples i found so far write to a new file.
i have tried the followign code but it seems to be corrupting the file after write sometime
juce::File source(“test.wav”);
AudioFormatReader* reader = formatManager.createReaderFor(source);
int64 startSample = reader->sampleRate * startTime;
int numSamples = (reader->sampleRate * endTime) - startSample;
juce::AudioSampleBuffer* buffer = new AudioSampleBuffer(reader->numChannels, numSamples);
reader->read(buffer, 0, numSamples, startSample, true, true);
// modify buffer
int bitdepth = (reader->bitsPerSample / 8);
int64 byte = (startSample * reader->numChannels * bitdepth);
juce::FileOutputStream* outStream = new juce::FileOutputStream(sourceFile);
juce::WavAudioFormat format;
juce::AudioFormatWriter* writer = format.createWriterFor(outStream, reader->sampleRate,
reader->numChannels, reader->bitsPerSample, {}, 0);
writer->writeFromAudioSampleBuffer(*buffer, 0, numSamples);
delete writer;

Because many audio formats don’t support altering parts of audio (e.g. because of compression), you will need to stream from the reading file to the output file and replace the audio once you get there.
This has also the benefit that in case the program crashes or is interrupted for whatever reason, the original file stays intact and only once you finished writing you move it to replace the original file.

The TemporaryFile is ideal for that use case.

N.B. if you add three backticks ``` before and after your code on a spparate line, it will be correctly formatted

N.B. 2: If you need to write delete, it is a strong sign that you need unique_ptrs:

std::unique_ptr<juce::AudioFormatWriter> writer (format.createWriterFor (outStream,
    reader->bitsPerSample, {}, 0));

hi daniel,
thanks for the reply. i was going to try what you suggested next writing to a different file first and renaming it to original file. just wanted to know if modifying parts of a file is supported at all or not (since i am new to juce ) and if its not supported why. could you please elaborate on N.B 1. i didn’t get it

Yes it is not supported, because in a compressed file the number of bytes needed might change when you alter the content. So the rest of the file would need to be rewritten anyway.

You might have realised that your code has no indent and some characters or even words are swallowed by the html processor. The forum uses a syntax called markdown. You can mark your code so it keeps the formatting by either indenting each line with at least 4 whitespaces or you surround your code with the backticks.
See also this link: Markdown Cheatsheet


ok got it thanks