c++ – Writing audio data to an existing audio file using the FFmpeg API

Question:

My main task is to record the received audio data into an existing file at the request of the client.

As an example, let's say I have already created an audio file with an audio recording length of 1 hour. I want to open it, record an additional 1 hour of audio data, and close it. As a result, we should get an audio file containing a 2-hour audio track. I understand correctly that in this case, if possible, I will have to delete the previously recorded trailer (it was recorded thanks to the av_write_trailer function), write the received data to the end of the file, and when I close the audio file, record the current trailer?

This is the code snippet where I record the trailer and close the media file:

// Writing the stream trailer to an output
// media file and free the file private data.
av_write_trailer(p_oFrmCtx);
avformat_close_input(&p_oFrmCtx);

It's important to note that the implementation of writing audio data to a new audio file works fine. The problem is exactly how to write the audio data to the existing audio file.

Answer:

In its general form, this problem has no solution. The ability to append data to an existing file is essentially impossible for most audio formats because it involves a combination of many factors: the file structure should assume the possibility of appending with or without the need to match the data formats of the existing and new parts; the implementation of the corresponding container must be explicitly adapted to the gluing; in most cases, the implementation will assume reading the entire available fragment before the first byte can be appended, often incl. using a temporary intermediate file / stream.

Of the traditional data formats, there are only a few examples, such as MPEG TS, where appending is in principle provided. As a standard, gluing occurs from ready-made pieces and by a full-scale re-creation of the file with data copying.

Scroll to Top