Recursive AI

Encode raw FLAC frames in C#

oneaudio is a free, open-source audio library for .NET from Recursive AI. MIT or Apache-2.0, no bundled native binaries.

Use FlacPacketEncoder to get compressed FLAC frames (packets) without a .flac file header.

Terminal
dotnet add package RecursiveAI.OneAudio

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneAudio;
using OneAudio.Flac;
 
var format = new AudioFormat(48000, 1);
using var flac = new FlacPacketEncoder(format);
int[] pcm = [-150, -50, 50, 150];
if (flac.WriteInteger(pcm) != pcm.Length)
    throw new InvalidOperationException();
flac.Finish();
if (!flac.TryReadPacket(out var packet))
    throw new InvalidOperationException();
byte[] frame = packet.Data.ToArray();
Console.WriteLine(packet.Samples);
Text
4

Unzip the example, then dotnet run.

The snippet encodes four signed mono samples and copies the packet bytes into frame.

The full program

For input longer than one block, loop over the number of frames accepted by WriteInteger. This program makes a 1,000-sample mono ramp in memory and uses a block size of 512 to show both a full frame and a shorter final one.

C#
using OneAudio;
using OneAudio.Flac;
 
// A 16-bit mono ramp with a partial final block.
var pcm = new int[1000];
for (int i = 0; i < pcm.Length; i++) pcm[i] = i - 500;
var format = new AudioFormat(48000, 1);
var settings = new FlacEncoderSettings
{
    BitsPerSample = 16,
    BlockSize = 512
};
using var encoder = new FlacPacketEncoder(format, settings);
var packets = new List<byte[]>();
for (int offset = 0; offset < pcm.Length;)
{
    offset += encoder.WriteInteger(pcm.AsSpan(offset));
    Drain();
}
encoder.Finish();
Drain();
Console.WriteLine($"Kept {packets.Count} raw FLAC frames in memory.");
 
if (args.Contains("--file"))
{
    using var file = File.Create("ramp.flac");
    file.Write("fLaC"u8);
    file.Write(encoder.GetStreamInfoBlock());
    foreach (var bytes in packets) file.Write(bytes);
    Console.WriteLine("Wrote ramp.flac.");
}
 
void Drain()
{
    while (encoder.TryReadPacket(out var packet))
    {
        packets.Add(packet.Data.ToArray());
        Console.WriteLine($"Frame {packet.Index}: " +
            $"start {packet.FirstSample}, samples {packet.Samples}");
    }
}
Text
Frame 0: start 0, samples 512
Frame 1: start 512, samples 488
Kept 2 raw FLAC frames in memory.

Copy packet.Data before the next encode if you need to keep it: the encoder reuses its frame buffer. Calling Finish with an unread full packet throws InvalidOperationException; drain after each write and once more after Finish.

Variations

Write a native FLAC file from the same packets. The full program can prefix them with the fLaC marker and a STREAMINFO block:

Terminal
dotnet run -- --file

After printing the two packet positions, it prints Wrote ramp.flac..


The short answer

Use FlacPacketEncoder when the receiver needs compressed FLAC audio frames with no file wrapper. Feed it interleaved PCM and drain TryReadPacket whenever you write input. Finish completes the stream and produces a last packet if there’s a partial block left. Each packet carries its bytes, the first sample position and the number of samples per channel, so you can pass both the payload and its position to a container writer. Use WriteInteger with signed PCM values at the chosen bit depth when you want to preserve those integers.

Can FLAC files have metadata if raw FLAC frames don’t?

Yes. The native FLAC layout in RFC 9639 is the fLaC marker, a required STREAMINFO block, optional other metadata blocks, then the compressed audio frames. STREAMINFO describes the stream as a whole, including bit depth, channel count and total sample count when known. A FLAC frame has its own header and checksum, but that’s not the same as having the file marker and stream metadata. Concatenating raw frame bytes and naming the result .flac leaves out the required beginning of the file.

How do I turn raw FLAC frames into a FLAC file?

Use GetStreamInfoBlock() after Finish to get the 34-byte STREAMINFO body plus its four-byte metadata header. In the --file variation it’s the only metadata block, so its last-block flag is set. The code writes that block after fLaC, then writes the packets in order. GetStreamInfo() is the body alone and isn’t a drop-in replacement for GetStreamInfoBlock() in this layout. If your destination is another container, use its own mapping for the configuration and packet boundaries; don’t prefix each packet with fLaC.

If you only need a standalone file, use the library’s FlacEncoder instead of saving every packet in memory. It writes the file structure to a stream and, when the stream is seekable, fills in final sizes and the PCM checksum on finish. Keep the packet API for cases where your application, or a separate container writer, owns the framing.

All oneaudio recipes