Recursive AI

Register a custom audio decoder in C#

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

Recognize a PCM8 header and read the three mono samples that follow it. PCM8 is a toy format made up for this example.

Terminal
dotnet add package RecursiveAI.OneAudio

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

To compile this snippet, copy Pcm8Format and Pcm8Decoder from the full program or use the ZIP, which includes both.

C#
using System;
using System.IO;
using OneAudio;
 
// Copy both PCM8 classes from the full program.
var registry = new AudioCodecRegistry()
    .Add(new Pcm8Format());
byte[] bytes = [.. "PCM8"u8, 0, 128, 192];
using var stream = new MemoryStream(bytes);
using var decoder =
    AudioDecoder.Open(stream, registry);
var samples = new float[3];
if (decoder.Read(samples) != 3)
    throw new InvalidOperationException(
        "Expected 3 frames.");
Console.WriteLine(decoder.GetType().Name);
var line = FormattableString.Invariant(
    $"{samples[0]}, {samples[1]}, {samples[2]}");
Console.WriteLine(line);

Unzip the example, then dotnet run.

Prints the selected decoder and its normalized samples:

Text
Pcm8Decoder
-1, 0, 0.5

The full program

The example’s entire format is four ASCII bytes (PCM8) followed by exactly three unsigned 8-bit samples at 8 kHz. The bytes are constructed in memory. This is not a WAV file. If no registered container recognizes the stream, AudioDecoder.Open throws UnsupportedAudioFormatException; a recognized PCM8 header with a wrong payload length is rejected by the example with AudioFormatException.

C#
using System;
using System.Globalization;
using System.IO;
using OneAudio;
 
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var registry = new AudioCodecRegistry().Add(new Pcm8Format());
using var input = new MemoryStream([.. "PCM8"u8, 0, 128, 192]);
using var decoder = AudioDecoder.Open(input, registry);
var samples = new float[3];
int frames = decoder.Read(samples);
if (decoder is not Pcm8Decoder || frames != 3)
    throw new InvalidOperationException("Expected three custom PCM8 frames.");
Console.WriteLine(decoder.GetType().Name);
Console.WriteLine(string.Join(", ", samples));
 
sealed class Pcm8Format : IContainerFormat
{
    public string Name => "PCM8";
    public bool Matches(ReadOnlySpan<byte> head) => head.StartsWith("PCM8"u8);
 
    public IAudioDecoder Open(Stream stream, AudioCodecRegistry registry,
        AudioLimits limits, bool leaveOpen, System.Threading.CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();
        if (limits.MaxSamples < 3)
            throw new AudioLimitExceededException(nameof(limits.MaxSamples), limits.MaxSamples, 3);
        if (limits.MaxSampleRate < 8000)
            throw new AudioLimitExceededException(nameof(limits.MaxSampleRate), limits.MaxSampleRate, 8000);
        if (limits.MaxChannels < 1)
            throw new AudioLimitExceededException(nameof(limits.MaxChannels), limits.MaxChannels, 1);
        Span<byte> data = stackalloc byte[7];
        if (stream.ReadAtLeast(data, data.Length, false) != data.Length ||
            !Matches(data) || stream.ReadByte() != -1)
            throw new AudioFormatException("Expected PCM8 followed by three bytes.");
        return new Pcm8Decoder(data[4..].ToArray(), stream, leaveOpen);
    }
}
 
sealed class Pcm8Decoder(byte[] data, Stream stream, bool leaveOpen) : IAudioDecoder
{
    private int position;
    public AudioFormat Format => new(8000, 1,
        NativeType: NativeSampleType.PcmUnsigned8, BitsPerSample: 8);
    public long LengthFrames => data.Length;
    public long PositionFrames => position;
    public bool CanSeek => true;
    public bool HasNativeIntegers => true;
 
    public int Read(Span<float> destination)
    {
        int count = Math.Min(destination.Length, data.Length - position);
        for (int i = 0; i < count; i++)
            destination[i] = (data[position++] - 128) / 128f;
        return count;
    }
 
    public int ReadInteger(Span<int> destination)
    {
        int count = Math.Min(destination.Length, data.Length - position);
        for (int i = 0; i < count; i++)
            destination[i] = data[position++] - 128;
        return count;
    }
 
    public void Seek(long frame)
    {
        if (frame < 0 || frame > data.Length)
            throw new ArgumentOutOfRangeException(nameof(frame));
        position = (int)frame;
    }
 
    public void Dispose()
    {
        if (!leaveOpen)
            stream.Dispose();
    }
}
Text
Pcm8Decoder
-1, 0, 0.5

Variations

Keep built-in WAV support

Replace the registry declaration in the snippet at the top. The same input still selects the custom decoder:

C#
var registry = new AudioCodecRegistry()
    .AddWav()
    .Add(new Pcm8Format());
Text
Pcm8Decoder
-1, 0, 0.5

The short answer

Implement IContainerFormat.Matches to recognize the leading bytes and IContainerFormat.Open to return an IAudioDecoder. Register an instance with new AudioCodecRegistry().Add(yourFormat) and pass that registry to AudioDecoder.Open. Registering a codec alone does not teach oneaudio to recognize a new file signature. The program verifies the type of decoder returned as well as reading the frames, so you can see that the registry actually picked the custom implementation.

What’s the difference between an audio container and a codec?

A container describes how the audio is laid out in a file; a codec turns the encoded audio payload into samples. Here, the container is a four-byte marker followed by three raw sample bytes. Its Open method can construct the decoder directly because there are no compressed packets to route. The decoder reports one channel at 8 kHz. Each byte is one frame, and the float read converts a byte with (byteValue - 128) / 128f: 128 is silence, 0 maps to -1, and 192 maps to 0.5. The integer read also centers the values at zero, but doesn’t divide them by 128.

If your container carries compressed packets instead, the registration API separates the two jobs. The container finds packet boundaries and exposes them as an IPacketSource; it looks up the codec by CodecId in the registry. Register that codec as an IAudioCodec and implement CreateDecoder to turn that packet source into an IAudioDecoder.

How does oneaudio detect which decoder to use?

When you call AudioDecoder.Open, oneaudio reads up to 512 leading bytes and checks registered containers. Strong signatures are tried before weak patterns and registration order breaks ties within each group. A container’s Matches should recognize its own header rather than claiming every stream it can possibly read. This example checks the marker in Matches and does the stricter length check when opening. When you call OpenFile by path, only if the leading bytes don’t match a container does oneaudio try the file extension. An unnamed stream has no extension fallback.

The registry starts empty and belongs to your application; it doesn’t install a system codec. Add built-in formats explicitly if that registry should handle them too. As the WAV variation shows, adding a second container doesn’t require changing the AudioDecoder.Open call, and the PCM8 signature still selects the example’s decoder.

All oneaudio recipes