-
-
Notifications
You must be signed in to change notification settings - Fork 2
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.
The easiest way to install OwnAudioSharp is using the NuGet Package Manager:
NuGet\Install-Package OwnAudioSharpOr in Visual Studio Package Manager Console:
Install-Package OwnAudioSharpOwnAudioSharp uses the built-in MiniAudio library by default, which works on all platforms. For additional functionality, you can install the following optional dependencies:
- Download FFmpeg 6 files and extract them to a folder
- Copy the PortAudio 2 DLL file to the same folder
- Specify the folder path when initializing OwnAudio
sudo apt update
sudo apt install portaudio19-dev ffmpegbrew install portaudio
brew install ffmpeg@6Let's start with a basic console application that can play audio files:
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);
}
}
}
}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;// 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// 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);
}
});- MiniAudio uses WASAPI by default
- FFmpeg and PortAudio can be used optionally for better performance
- ALSA support is built-in
- Installing FFmpeg and PortAudio is recommended:
sudo apt install portaudio19-dev ffmpeg
- Core Audio support is built-in
- Extensions can be installed with Homebrew:
brew install portaudio ffmpeg@6
- Only MiniAudio is supported
- No external dependencies required
// 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;
}// 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
);Create a new Console App project and add the following files:
<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>dotnet build
dotnet runNow that you've learned the basics of OwnAudioSharp, try these advanced features:
- Audio visualization - Using WaveAvaloniaDisplay
- Chord recognition - Trying the DetectChords function
- Game development - Using SourceSpark for sound effects
- Audio processing - Writing custom effects
- Mobile development - Creating Android/iOS applications
For more information, visit the [GitHub repository](https://github.com/ModernMube/OwnAudioSharp) wiki pages!
- Documentation: Check out the comprehensive API documentation
- Sample Applications: [OwnAudioSharpDemo](https://github.com/ModernMube/OwnAudioSharpDemo) - Avalonia MVVM demo
- Support: Visit the GitHub issues page for community support
- Contributing: Contributions are welcome! See the contributing guidelines
This project is open source. Please check the repository for license information.
Happy coding with OwnAudioSharp! 🎵