Skip to content

OwnAudioSharp Beginner's Guide

ModernMusician edited this page Aug 16, 2025 · 1 revision

OwnAudioSharp Beginner's Guide

In this guide, we'll learn step by step how to use the OwnAudioSharp library by creating a simple audio player. The library is cross-platform, so it works on Windows, macOS, Linux, Android, and iOS systems.

1. Installation

Installing NuGet Package

The easiest way to install OwnAudioSharp is using the NuGet Package Manager:

NuGet\Install-Package OwnAudioSharp

Or in Visual Studio Package Manager Console:

Install-Package OwnAudioSharp

Optional Dependencies (for better performance)

OwnAudioSharp uses the built-in MiniAudio library by default, which works on all platforms. For additional functionality, you can install the following optional dependencies:

Windows

  1. Download FFmpeg 6 files and extract them to a folder
  2. Copy the PortAudio 2 DLL file to the same folder
  3. Specify the folder path when initializing OwnAudio

Linux (Ubuntu/Debian)

sudo apt update
sudo apt install portaudio19-dev ffmpeg

macOS (Homebrew)

brew install portaudio
brew install ffmpeg@6

2. Simple Console Audio Player

Let's start with a basic console application that can play audio files:

Program.cs

using System;
using System.Threading.Tasks;
using Ownaudio;
using Ownaudio.Sources;

namespace SimpleAudioPlayer
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("OwnAudioSharp Simple Audio Player");
            Console.WriteLine("==================================");

            try
            {
                // 1. Initialize OwnAudio
                if (!OwnAudio.Initialize())
                {
                    Console.WriteLine("Error: Failed to initialize audio system!");
                    return;
                }

                Console.WriteLine("Audio system successfully initialized.");

                // 2. Get SourceManager instance
                var sourceManager = SourceManager.Instance;

                // 3. Load audio file
                Console.Write("Enter the audio file path: ");
                string? audioPath = Console.ReadLine();

                if (string.IsNullOrEmpty(audioPath))
                {
                    Console.WriteLine("Valid file path is required!");
                    return;
                }

                Console.WriteLine("Loading audio file...");
                bool isLoaded = await sourceManager.AddOutputSource(audioPath, "MainTrack");

                if (!isLoaded)
                {
                    Console.WriteLine("Error: Failed to load audio file!");
                    return;
                }

                Console.WriteLine($"Successfully loaded! Duration: {sourceManager.Duration}");

                // 4. Playback control
                await PlaybackControl(sourceManager);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error occurred: {ex.Message}");
            }
            finally
            {
                // 5. Free resources
                OwnAudio.Free();
                Console.WriteLine("Resources freed. Press any key to exit...");
                Console.ReadKey();
            }
        }

        static async Task PlaybackControl(SourceManager sourceManager)
        {
            bool isRunning = true;

            Console.WriteLine("\nControls:");
            Console.WriteLine("P - Play/Pause");
            Console.WriteLine("S - Stop");
            Console.WriteLine("R - Restart");
            Console.WriteLine("+ - Volume up");
            Console.WriteLine("- - Volume down");
            Console.WriteLine("Q - Quit");

            while (isRunning)
            {
                Console.Write($"\rState: {sourceManager.State} | " +
                             $"Position: {sourceManager.Position:mm\\:ss}/{sourceManager.Duration:mm\\:ss} | " +
                             $"Volume: {sourceManager.Volume:P0} | Command: ");

                var key = Console.ReadKey(true);

                switch (char.ToUpper(key.KeyChar))
                {
                    case 'P':
                        if (sourceManager.State == SourceState.Playing)
                        {
                            sourceManager.Pause();
                        }
                        else
                        {
                            sourceManager.Play();
                        }
                        break;

                    case 'S':
                        sourceManager.Stop();
                        break;

                    case 'R':
                        sourceManager.Stop();
                        sourceManager.Seek(TimeSpan.Zero);
                        sourceManager.Play();
                        break;

                    case '+':
                    case '=':
                        sourceManager.Volume = Math.Min(1.0f, sourceManager.Volume + 0.1f);
                        break;

                    case '-':
                        sourceManager.Volume = Math.Max(0.0f, sourceManager.Volume - 0.1f);
                        break;

                    case 'Q':
                        sourceManager.Stop();
                        isRunning = false;
                        break;
                }

                await Task.Delay(100);
            }
        }
    }
}

3. Advanced Features

Applying Audio Effects

using Ownaudio.Fx;

// Add reverb effect
var reverb = new Reverb(roomSize: 0.7f, damping: 0.5f, wetLevel: 0.3f);
sourceManager.CustomSampleProcessor = reverb;

// Using equalizer
var equalizer = new Equalizer(44100);
equalizer.SetBandGain(0, 100f, 1.4f, 3.0f);  // Bass boost
sourceManager.CustomSampleProcessor = equalizer;

Mixing Multiple Audio Sources

// Add multiple audio files
await sourceManager.AddOutputSource("background.mp3", "Background");
await sourceManager.AddOutputSource("effects.wav", "Effects");

// Set individual volume for sources
sourceManager["Background"].Volume = 0.6f;
sourceManager["Effects"].Volume = 0.8f;

// Pitch and tempo modification
sourceManager["Background"].Pitch = -2.0;  // 2 semitones down
sourceManager["Effects"].Tempo = 10.0;     // 10% faster

Real-time Audio Generation

// Create real-time source
var realtimeSource = sourceManager.AddRealTimeSource(1.0f, 2, "Synthesizer");

// Generate sine wave
await Task.Run(async () =>
{
    int sampleRate = 44100;
    int frequency = 440; // A4 note
    float amplitude = 0.3f;
    
    double phase = 0;
    double phaseIncrement = 2.0 * Math.PI * frequency / sampleRate;
    
    for (int i = 0; i < 1000; i++) // 1000 buffers
    {
        float[] buffer = new float[1024 * 2]; // Stereo
        
        for (int j = 0; j < 1024; j++)
        {
            float sample = (float)(Math.Sin(phase) * amplitude);
            buffer[j * 2] = sample;     // Left channel
            buffer[j * 2 + 1] = sample; // Right channel
            
            phase += phaseIncrement;
            if (phase >= 2.0 * Math.PI)
                phase -= 2.0 * Math.PI;
        }
        
        realtimeSource.SubmitSamples(buffer);
        await Task.Delay(10);
    }
});

4. Platform-Specific Notes

Windows

  • MiniAudio uses WASAPI by default
  • FFmpeg and PortAudio can be used optionally for better performance

Linux

  • ALSA support is built-in
  • Installing FFmpeg and PortAudio is recommended: sudo apt install portaudio19-dev ffmpeg

macOS

  • Core Audio support is built-in
  • Extensions can be installed with Homebrew: brew install portaudio ffmpeg@6

Android/iOS

  • Only MiniAudio is supported
  • No external dependencies required

5. Troubleshooting and Common Issues

Audio doesn't play

// Check initialization
if (!OwnAudio.Initialize())
{
    Console.WriteLine("Audio system initialization failed!");
    return;
}

// Check source loading
bool loaded = await sourceManager.AddOutputSource("test.mp3");
if (!loaded)
{
    Console.WriteLine("Audio file loading failed!");
    return;
}

Performance optimization

// Set buffer size (smaller = less latency, more CPU)
SourceManager.EngineFramesPerBuffer = 256; // Default: 512

// Configure audio quality
SourceManager.OutputEngineOptions = new AudioEngineOutputOptions(
    OwnAudioEngine.EngineChannels.Stereo,
    44100, // Sample rate
    0.02   // Low latency
);

6. Complete Example Project

Create a new Console App project and add the following files:

SimpleAudioPlayer.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  
  <ItemGroup>
    <PackageReference Include="OwnAudioSharp" Version="Latest" />
  </ItemGroup>
</Project>

Program.cs (the complete code above)

Running

dotnet build
dotnet run

Next Steps

Now that you've learned the basics of OwnAudioSharp, try these advanced features:

  1. Audio visualization - Using WaveAvaloniaDisplay
  2. Chord recognition - Trying the DetectChords function
  3. Game development - Using SourceSpark for sound effects
  4. Audio processing - Writing custom effects
  5. Mobile development - Creating Android/iOS applications

For more information, visit the [GitHub repository](https://github.com/ModernMube/OwnAudioSharp) wiki pages!


Additional Resources

License

This project is open source. Please check the repository for license information.


Happy coding with OwnAudioSharp! 🎵