How to Encode and Decode FLAC with FlacLibSharp
This guide shows a practical, minimal workflow for encoding WAV to FLAC and decoding FLAC back to PCM using FlacLibSharp in a .NET application. Examples assume C# (.NET 6+) and use synchronous, memory- and file-based operations. Adjust buffer sizes and threading for production use.
What you need
- .NET 6+ SDK
- FlacLibSharp NuGet package (or library binaries)
- A WAV file (PCM 16-bit) to encode, or a FLAC file to decode
Quick setup
- Add FlacLibSharp to your project:
- Using dotnet CLI:
dotnet add package FlacLibSharp
- Using dotnet CLI:
- Include namespaces in your C# files:
csharp
using Flac;using System.IO;
Encoding WAV (PCM 16-bit) to FLAC
This example reads a 16-bit PCM WAV file (stereo or mono), extracts sample data, and encodes it to FLAC.
csharp
using System;using System.IO;using Flac; // adjust to actual FlacLibSharp namespace public static class FlacEncoderExample{ public static void EncodeWavToFlac(string wavPath, string flacPath) { using var wav = new FileStream(wavPath, FileMode.Open, FileAccess.Read); using var reader = new BinaryReader(wav); // Minimal WAV header parse (assumes standard PCM WAV) reader.ReadChars(4); // “RIFF” reader.ReadInt32(); // file size reader.ReadChars(4); // “WAVE” reader.ReadChars(4); // “fmt ” int fmtChunkSize = reader.ReadInt32(); int audioFormat = reader.ReadInt16(); int channels = reader.ReadInt16(); int sampleRate = reader.ReadInt32(); reader.ReadInt32(); // byte rate reader.ReadInt16(); // block align int bitsPerSample = reader.ReadInt16(); // Skip any extra fmt bytes if (fmtChunkSize > 16) reader.ReadBytes(fmtChunkSize - 16); // Find “data” chunk while (new string(reader.ReadChars(4)) != “data”) { int chunkSize = reader.ReadInt32(); reader.ReadBytes(chunkSize); } int dataSize = reader.ReadInt32(); if (audioFormat != 1 || bitsPerSample != 16) throw new NotSupportedException(“Only 16-bit PCM WAV supported in this example.”); int totalSamples = dataSize / (bitsPerSample / 8) / channels; short[] samples = new short[totalSampleschannels]; for (int i = 0; i < samples.Length; i++) samples[i] = reader.ReadInt16(); // Create encoder (API names may vary — adapt to actual FlacLibSharp API) var encoder = new FlacEncoder(); encoder.SetChannels(channels); encoder.SetBitsPerSample(bitsPerSample); encoder.SetSampleRate(sampleRate); encoder.SetCompressionLevel(5); // 0-8 typical if (!encoder.Init(flacPath)) throw new Exception(“FLAC encoder init failed.”); // Feed frames (convert short[] to int[] if required by API) int frameSize = 1024; int pos = 0; while (pos < totalSamples) { int currentFrame = Math.Min(frameSize, totalSamples - pos); int[][] buffer = new int[channels][]; for (int ch = 0; ch < channels; ch++) { buffer[ch] = new int[currentFrame]; for (int i = 0; i < currentFrame; i++) { buffer[ch][i] = samples[(pos + i) * channels + ch]; } } if (!encoder.Process(buffer, currentFrame)) { encoder.Finish(); throw new Exception(“Encoding error.”); } pos += currentFrame; } encoder.Finish(); }}
Notes:
- FlacLibSharp API names may differ; adapt method names (e.g., FlacEncoder, Init, Process) to the package version you install.
- For large files, stream and encode in chunks instead of loading all samples into memory.
- For floating-point WAV input, convert samples to integer PCM or use a floating-point-capable encoder if available.
Decoding FLAC to PCM WAV
This example decodes a FLAC file to a 16-bit PCM WAV file.
csharp
using System;using System.IO;using Flac; // adjust to actual FlacLibSharp namespace public static class FlacDecoderExample{ public static void DecodeFlacToWav(string flacPath, string wavPath) { var decoder = new FlacDecoder(); // adapt to actual API if (!decoder.Init(flacPath)) throw new Exception(“FLAC decoder init failed.”); int channels = decoder.Channels; int sampleRate = decoder.SampleRate; int bitsPerSample = decoder.BitsPerSample; using var outFs = new FileStream(wavPath, FileMode.Create, FileAccess.Write); using var writer = new BinaryWriter(outFs); // Write WAV header placeholder writer.Write(System.Text.Encoding.ASCII.GetBytes(“RIFF”)); writer.Write(0); // placeholder file size writer.Write(System.Text
Leave a Reply