Core Ownaudio.Core API Reference

Low-level cross-platform audio engine with native C++ core (default) or managed C# implementations. Built without external dependencies using native system audio APIs.

🚀 Native Engine (Default) The native C++ engine is now the default, providing GC-free, glitch-free audio. Despite extensive optimization efforts with managed code (zero-allocation design, lock-free structures), the .NET Garbage Collector proved to be an insurmountable challenge for real-time audio. The managed engines remain available for development/testing.
Zero External Dependencies Ownaudio.Core uses native system audio APIs directly: WASAPI (Windows), Core Audio (macOS/iOS), PulseAudio (Linux), and Oboe (Android). No additional libraries required!

Overview

Ownaudio.Core provides the foundation for cross-platform audio applications with:

Engine Types

Engine Type Implementation GC Behavior Use Case
Native (Default) C++ core No GC interference Production, professional audio
Managed (Optional) Pure C# Subject to GC pauses Development, testing, debugging

Supported Platforms

Platform Native API Assembly
Windows WASAPI Ownaudio.Windows
macOS Core Audio Ownaudio.macOS
Linux PulseAudio Ownaudio.Linux
iOS Core Audio Ownaudio.iOS
Android AAudio Ownaudio.Android

Interfaces

IAudioEngine

Platform-independent audio engine interface for real-time playback and recording.

IAudioEngine Interface
public interface IAudioEngine
{
    // Properties
    int FramesPerBuffer { get; }
    
    // Lifecycle Methods
    int Initialize(AudioConfig config);
    int Start();
    int Stop();
    int OwnAudioEngineActivate();
    int OwnAudioEngineStopped();
    
    // Audio I/O
    void Send(Span<float> samples);
    int Receives(out float[] samples);
    IntPtr GetStream();
    
    // Device Management
    List<AudioDeviceInfo> GetOutputDevices();
    List<AudioDeviceInfo> GetInputDevices();
    int SetOutputDeviceByName(string deviceName);
    int SetOutputDeviceByIndex(int deviceIndex);
    int SetInputDeviceByName(string deviceName);
    int SetInputDeviceByIndex(int deviceIndex);
    
    // Events
    event EventHandler<AudioDeviceChangedEventArgs> OutputDeviceChanged;
    event EventHandler<AudioDeviceChangedEventArgs> InputDeviceChanged;
    event EventHandler<AudioDeviceStateChangedEventArgs> DeviceStateChanged;
}

Properties

Property Type Description
FramesPerBuffer int Actual buffer size in frames (may differ from requested)

Methods

Method Return Description
Initialize(AudioConfig) int Initialize engine. Returns 0 on success, negative on error
Start() int Start audio engine (thread-safe, idempotent)
Stop() int Stop audio engine (thread-safe, idempotent)
Send(Span<float>) void Send audio samples (blocking, zero-allocation)
Receives(out float[]) int Receive audio samples (pooled buffer). Returns sample count
GetOutputDevices() List Get list of available output devices
GetInputDevices() List Get list of available input devices

Usage Example

Basic Engine Usage
// Create and initialize engine
using var engine = AudioEngineFactory.CreateDefault();
engine.Initialize(AudioConfig.Default);

// Start the engine
engine.Start();

// Send audio samples
float[] samples = GenerateAudio();
engine.Send(samples.AsSpan());

// Stop the engine
engine.Stop();

IAudioDecoder

Audio file decoder interface for WAV, MP3, and FLAC formats.

IAudioDecoder Interface
public interface IAudioDecoder : IDisposable
{
    AudioStreamInfo StreamInfo { get; }
    
    AudioDecoderResult DecodeNextFrame();
    bool TrySeek(TimeSpan position, out string error);
    AudioDecoderResult DecodeAllFrames(TimeSpan position);
}

Properties

Property Type Description
StreamInfo AudioStreamInfo Information about the loaded audio stream

Methods

Method Return Description
DecodeNextFrame() AudioDecoderResult Decode next audio frame
TrySeek(TimeSpan, out string) bool Seek to position. Returns true on success
DecodeAllFrames(TimeSpan) AudioDecoderResult Decode all frames from position

Usage Example

Decoder Usage
// Create decoder
using var decoder = AudioDecoderFactory.Create(
    "music.mp3",
    targetSampleRate: 48000,
    targetChannels: 2
);

// Get stream info
var info = decoder.StreamInfo;
Console.WriteLine($"Duration: {info.Duration}");

// Decode frames
while (true)
{
    var result = decoder.DecodeNextFrame();
    if (result.IsEOF) break;
    
    // Process frame
    ProcessAudioFrame(result.Frame);
}

// Seek to position
if (decoder.TrySeek(TimeSpan.FromSeconds(30), out string error))
{
    Console.WriteLine("Seeked to 30 seconds");
}

Factory Classes

AudioEngineFactory

Creates platform-specific audio engine instances.

Method Description
Create(AudioConfig) Create engine with custom configuration
CreateDefault() Create with default settings (48kHz, stereo, 512 frames)
CreateLowLatency() Create with low latency settings (128 frames)
CreateHighLatency() Create with high latency settings (2048 frames)
GetPlatformInfo() Get current platform information string
Factory Usage
// Default configuration
using var engine1 = AudioEngineFactory.CreateDefault();

// Low latency
using var engine2 = AudioEngineFactory.CreateLowLatency();

// Custom configuration
var config = new AudioConfig
{
    SampleRate = 44100,
    Channels = 2,
    BufferSize = 256
};
using var engine3 = AudioEngineFactory.Create(config);

// Platform info
string platform = AudioEngineFactory.GetPlatformInfo();
Console.WriteLine($"Platform: {platform}"); // e.g., "Windows-WASAPI"

AudioDecoderFactory

Creates audio decoders based on file format.

Method Description
Create(string, int, int) Create decoder from file path with target sample rate and channels
Create(Stream, AudioFormat, int, int) Create decoder from stream with specified format

Supported Formats

Format Types Implementation
WAV PCM, IEEE Float, ADPCM Pure C# implementation
MP3 MPEG-1/2 Layer III Platform-specific or managed fallback
FLAC Free Lossless Audio Codec Pure C# managed implementation
Decoder Factory Usage
// From file path (auto-detect format)
using var decoder1 = AudioDecoderFactory.Create(
    "music.mp3",
    targetSampleRate: 48000,
    targetChannels: 2
);

// From stream with explicit format
using var stream = File.OpenRead("audio.wav");
using var decoder2 = AudioDecoderFactory.Create(
    stream,
    AudioFormat.Wav,
    targetSampleRate: 48000,
    targetChannels: 2
);

Configuration Classes

AudioConfig

Audio engine configuration parameters.

Property Type Default Description
SampleRate int 48000 Sample rate in Hz (typical: 44100, 48000, 96000)
Channels int 2 Number of channels (1=mono, 2=stereo)
BufferSize int 512 Buffer size in frames (affects latency)
EnableInput bool false Enable audio input/recording
EnableOutput bool true Enable audio output/playback
OutputDeviceId string? null Specific output device ID (null for default)
InputDeviceId string? null Specific input device ID (null for default)

Predefined Configurations

Configuration Example
// Use predefined config
var config1 = AudioConfig.Default;

// Custom configuration
var config2 = new AudioConfig
{
    SampleRate = 44100,
    Channels = 1,           // Mono
    BufferSize = 256,       // Low latency
    EnableInput = true,
    EnableOutput = true
};

// Validate configuration
if (config2.Validate())
{
    Console.WriteLine("Configuration is valid");
}

AudioDeviceInfo

Information about an audio device.

Property Type Description
DeviceId string Unique device identifier
Name string Human-readable device name
IsInput bool True if device supports input
IsOutput bool True if device supports output
IsDefault bool True if this is the default device
State AudioDeviceState Current device state
Device Enumeration
using var engine = AudioEngineFactory.CreateDefault();
engine.Initialize(AudioConfig.Default);

// List output devices
var devices = engine.GetOutputDevices();
foreach (var device in devices)
{
    Console.WriteLine($"Device: {device.Name}");
    Console.WriteLine($"  ID: {device.DeviceId}");
    Console.WriteLine($"  Default: {device.IsDefault}");
    Console.WriteLine($"  State: {device.State}");
}

AudioStreamInfo

Information about an audio stream.

Property Type Description
SampleRate int Sample rate in Hz
Channels int Number of channels
Duration TimeSpan Total duration of the stream
TotalFrames long Total number of frames

Enumerations

AudioDeviceState

Possible states of an audio device.

AudioDeviceState Enum
[Flags]
public enum AudioDeviceState
{
    Active      = 0x00000001,  // Device is active and available
    Disabled    = 0x00000002,  // Device is disabled
    NotPresent  = 0x00000004,  // Device is not present
    Unplugged   = 0x00000008,  // Device is unplugged
    All         = 0x0000000F   // All device states
}

AudioFormat

Supported audio file formats.

AudioFormat Enum
public enum AudioFormat
{
    Unknown,  // Unknown format
    Wav,      // WAV format (PCM, IEEE Float, ADPCM)
    Mp3,      // MP3 format (MPEG-1/2/2.5 Layer III)
    Flac      // FLAC format (Free Lossless Audio Codec)
}

Common Components

The Ownaudio.Core.Common namespace provides utility classes for audio processing:

Class Description
AudioBuffer Efficient audio buffer management
AudioChannelConverter Channel conversion (mono/stereo)
AudioResampler Sample rate conversion
AudioFormatConverter Format conversion utilities
LockFreeRingBuffer Lock-free circular buffer for real-time audio
AudioFramePool Object pool for audio frames
SimdAudioConverter SIMD-optimized audio conversion
DecodedAudioCache Cache for decoded audio data

Performance Characteristics

Zero-Allocation Guarantee

Critical audio paths use zero-allocation techniques:

Latency

Buffer Size Latency @ 48kHz Use Case
128 frames ~2.7 ms Professional audio, live monitoring
256 frames ~5.3 ms Low latency applications
512 frames ~10.7 ms Default, balanced performance
1024 frames ~21.3 ms Standard applications
2048 frames ~42.7 ms High reliability, less CPU usage

CPU Usage

Memory

Thread Safety All public APIs are thread-safe. Internal audio processing uses lock-free data structures for real-time performance.

Related Documentation