### Install OpusDotNet Package Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Instructions for installing the OpusDotNet library using NuGet or the .NET CLI. ```bash Install-Package OpusDotNet ``` ```bash dotnet add package OpusDotNet ``` -------------------------------- ### Install OpusDotNet NuGet Package Source: https://github.com/mrphil2105/opusdotnet/blob/master/README.md This command installs the OpusDotNet library using the NuGet Package Manager. OpusDotNet is a wrapper for libopus, facilitating audio encoding and decoding. ```powershell Install-Package OpusDotNet ``` -------------------------------- ### Configure Opus Application Mode Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Demonstrates how to initialize the OpusEncoder with different Application modes (VoIP, Audio, RestrictedLowDelay) to optimize for speech, music, or low-latency requirements. ```csharp using OpusDotNet; using (var voipEncoder = new OpusEncoder(Application.VoIP, 48000, 1)) { } using (var audioEncoder = new OpusEncoder(Application.Audio, 48000, 2)) { } using (var lowDelayEncoder = new OpusEncoder(Application.RestrictedLowDelay, 48000, 1)) { } ``` -------------------------------- ### Encode PCM Audio with OpusEncoder Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Demonstrates how to initialize an OpusEncoder and convert raw 16-bit PCM audio into compressed Opus format with custom encoding parameters. ```csharp using OpusDotNet; using (var encoder = new OpusEncoder(Application.VoIP, 48000, 2)) { encoder.VBR = true; encoder.Complexity = 10; encoder.FEC = true; encoder.ExpectedPacketLoss = 10; encoder.DTX = true; int frameSizeMs = 20; int pcmLength = frameSizeMs * 48000 / 1000 * 2 * 2; byte[] pcmBytes = new byte[pcmLength]; int targetBitrate = 128000; int opusBufferLength = targetBitrate * frameSizeMs / 8 / 1000; byte[] opusBytes = new byte[opusBufferLength]; int encodedLength = encoder.Encode(pcmBytes, pcmLength, opusBytes, opusBufferLength); Console.WriteLine($"Encoded {pcmLength} PCM bytes to {encodedLength} Opus bytes"); } ``` -------------------------------- ### Configure Audio Parameters and Buffer Sizes Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Provides reference arrays for supported sample rates and frame sizes in OpusDotNet. Includes a helper function to calculate the required PCM buffer size based on sample rate, channels, and frame duration. ```csharp int[] validSampleRates = { 8000, 12000, 16000, 24000, 48000 }; double[] validFrameSizes = { 2.5, 5, 10, 20, 40, 60 }; int CalculatePcmBufferSize(int sampleRate, int channels, double frameSizeMs) { return (int)(frameSizeMs * sampleRate / 1000 * channels * 2); } ``` -------------------------------- ### Decode Opus Audio with OpusDecoder Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Shows how to initialize an OpusDecoder to convert compressed Opus packets back into raw 16-bit PCM audio data. ```csharp using OpusDotNet; using (var decoder = new OpusDecoder(48000, 2)) { byte[] opusPacket = /* your compressed Opus data */; int opusLength = opusPacket.Length; int frameSizeMs = 20; int pcmBufferLength = frameSizeMs * 48000 / 1000 * 2 * 2; byte[] pcmBytes = new byte[pcmBufferLength]; int decodedLength = decoder.Decode(opusPacket, opusLength, pcmBytes, pcmBufferLength); Console.WriteLine($"Decoded {opusLength} Opus bytes to {decodedLength} PCM bytes"); } ``` -------------------------------- ### C# Audio Encoding and Decoding with OpusDotNet Source: https://github.com/mrphil2105/opusdotnet/blob/master/README.md Demonstrates basic audio encoding and decoding using OpusDotNet in C#. It initializes an OpusEncoder and OpusDecoder, encodes silence into Opus format, and then decodes it back to PCM. This is useful for VoIP applications. ```csharp using (var encoder = new OpusEncoder(Application.Audio, 48000, 2)) { encoder.Bitrate = 128000; // 128 kbps encoder.VBR = true; // Variable bitrate } using (var decoder = new OpusDecoder(48000, 2)) { // 40 ms of silence at 48 KHz (2 channels). byte[] inputPCMBytes = new byte[40 * 48000 / 1000 * 2 * 2]; byte[] opusBytes = encoder.Encode(inputPCMBytes, inputPCMBytes.Length, out int encodedLength); byte[] outputPCMBytes = decoder.Decode(opusBytes, encodedLength, out int decodedLength); } ``` -------------------------------- ### OpusDecoder Usage Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Illustrates how to use the OpusDecoder class to decode Opus-compressed audio back into raw PCM format. It includes setting up the decoder and processing received Opus packets. ```APIDOC ## OpusDecoder Usage ### Description This section demonstrates the usage of the `OpusDecoder` class for decoding Opus-compressed audio data back into raw 16-bit PCM format. It covers initializing the decoder and performing the decoding operation on received Opus packets. ### Method N/A (Class Usage) ### Endpoint N/A (Class Usage) ### Parameters N/A (Class Usage) ### Request Example ```csharp using OpusDotNet; // Create a decoder for 48 kHz stereo output using (var decoder = new OpusDecoder(48000, 2)) { // Received Opus packet from network or file byte[] opusPacket = /* your compressed Opus data */; int opusLength = opusPacket.Length; // Allocate PCM output buffer for 20ms at 48 kHz stereo int frameSizeMs = 20; int pcmBufferLength = frameSizeMs * 48000 / 1000 * 2 * 2; // 3840 bytes byte[] pcmBytes = new byte[pcmBufferLength]; // Decode the audio int decodedLength = decoder.Decode(opusPacket, opusLength, pcmBytes, pcmBufferLength); // Use pcmBytes[0..decodedLength] for playback Console.WriteLine($"Decoded {opusLength} Opus bytes to {decodedLength} PCM bytes"); } ``` ### Response N/A (Class Usage) ### Response Example N/A (Class Usage) ``` -------------------------------- ### OpusEncoder Usage Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Demonstrates how to use the OpusEncoder class to encode raw PCM audio data into Opus format. It covers initialization, configuration of encoding parameters, and the encoding process. ```APIDOC ## OpusEncoder Usage ### Description This section shows how to initialize and use the `OpusEncoder` class to convert raw 16-bit PCM audio into the compressed Opus format. It includes examples of setting various encoding parameters like sample rate, channels, bitrate, VBR, FEC, DTX, and the actual encoding process. ### Method N/A (Class Usage) ### Endpoint N/A (Class Usage) ### Parameters N/A (Class Usage) ### Request Example ```csharp using OpusDotNet; // Create an encoder for VoIP audio at 48 kHz stereo using (var encoder = new OpusEncoder(Application.VoIP, 48000, 2)) { // Configure encoder settings encoder.VBR = true; // Enable variable bitrate encoder.Complexity = 10; // Maximum quality (0-10) encoder.FEC = true; // Enable forward error correction encoder.ExpectedPacketLoss = 10; // Expect 10% packet loss encoder.DTX = true; // Enable discontinuous transmission // 20 ms of audio at 48 kHz stereo (20 * 48000 / 1000 * 2 channels * 2 bytes per sample) int frameSizeMs = 20; int pcmLength = frameSizeMs * 48000 / 1000 * 2 * 2; // 3840 bytes byte[] pcmBytes = new byte[pcmLength]; // Fill pcmBytes with your audio data... // Output buffer - size determines bitrate (e.g., 128 kbps for 20ms = 320 bytes) int targetBitrate = 128000; // 128 kbps int opusBufferLength = targetBitrate * frameSizeMs / 8 / 1000; byte[] opusBytes = new byte[opusBufferLength]; // Encode the audio int encodedLength = encoder.Encode(pcmBytes, pcmLength, opusBytes, opusBufferLength); // Use opusBytes[0..encodedLength] for transmission or storage Console.WriteLine($"Encoded {pcmLength} PCM bytes to {encodedLength} Opus bytes"); } ``` ### Response N/A (Class Usage) ### Response Example N/A (Class Usage) ``` -------------------------------- ### Implement Real-time Audio Encoding and Decoding with OpusDotNet Source: https://context7.com/mrphil2105/opusdotnet/llms.txt This class encapsulates the Opus encoder and decoder to process audio frames. It includes methods for calculating frame sizes, encoding PCM data, decoding Opus packets, and handling packet loss via FEC. ```csharp using System; using OpusDotNet; public class OpusAudioProcessor : IDisposable { private readonly OpusEncoder _encoder; private readonly OpusDecoder _decoder; private readonly int _frameSizeMs; private readonly int _sampleRate; private readonly int _channels; public OpusAudioProcessor(int sampleRate = 48000, int channels = 2, int frameSizeMs = 20) { _sampleRate = sampleRate; _channels = channels; _frameSizeMs = frameSizeMs; _encoder = new OpusEncoder(Application.VoIP, sampleRate, channels) { VBR = true, Complexity = 5, FEC = true, ExpectedPacketLoss = 5 }; _decoder = new OpusDecoder(sampleRate, channels); } public int GetPcmFrameSize() { return _frameSizeMs * _sampleRate / 1000 * _channels * 2; } public (byte[] opusData, int length) Encode(byte[] pcmData, int targetBitrate = 64000) { int pcmLength = GetPcmFrameSize(); if (pcmData.Length < pcmLength) { throw new ArgumentException($"PCM data must be at least {pcmLength} bytes"); } int opusBufferSize = targetBitrate * _frameSizeMs / 8 / 1000; byte[] opusBytes = new byte[opusBufferSize]; try { int encodedLength = _encoder.Encode(pcmData, pcmLength, opusBytes, opusBufferSize); return (opusBytes, encodedLength); } catch (OpusException ex) { Console.WriteLine($"Encoding error: {ex.Error} - {ex.Message}"); throw; } } public (byte[] pcmData, int length) Decode(byte[] opusData, int opusLength) { int pcmBufferSize = GetPcmFrameSize(); byte[] pcmBytes = new byte[pcmBufferSize]; try { int decodedLength = _decoder.Decode(opusData, opusLength, pcmBytes, pcmBufferSize); return (pcmBytes, decodedLength); } catch (OpusException ex) { Console.WriteLine($"Decoding error: {ex.Error} - {ex.Message}"); throw; } } public (byte[] pcmData, int length) HandlePacketLoss() { int pcmBufferSize = GetPcmFrameSize(); byte[] pcmBytes = new byte[pcmBufferSize]; int recoveredLength = _decoder.Decode(null, -1, pcmBytes, pcmBufferSize); return (pcmBytes, recoveredLength); } public void Dispose() { _encoder?.Dispose(); _decoder?.Dispose(); } } ``` -------------------------------- ### Force Encoder Channels Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Explains how to override automatic channel selection by setting the ForceChannels property to Mono or Stereo. ```csharp using OpusDotNet; using (var encoder = new OpusEncoder(Application.Audio, 48000, 2)) { encoder.ForceChannels = ForceChannels.Mono; } ``` -------------------------------- ### Handle OpusException in C# Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Demonstrates how to catch and handle specific Opus codec errors using the OpusException class. It includes a switch statement to map OpusError enums to user-friendly messages. ```csharp try { using (var encoder = new OpusEncoder(Application.VoIP, 48000, 2)) { byte[] invalidPcm = new byte[100]; byte[] opus = new byte[256]; encoder.Encode(invalidPcm, 100, opus, 256); } } catch (OpusException ex) { switch (ex.Error) { case OpusError.BadArg: Console.WriteLine("Invalid arguments provided"); break; case OpusError.BufferTooSmall: Console.WriteLine("Output buffer is too small"); break; case OpusError.InvalidPacket: Console.WriteLine("Corrupted audio data"); break; case OpusError.InternalError: Console.WriteLine("Internal Opus error"); break; case OpusError.InvalidState: Console.WriteLine("Encoder/decoder state is invalid"); break; case OpusError.AllocFail: Console.WriteLine("Memory allocation failed"); break; default: Console.WriteLine($"Opus error: {ex.Message}"); break; } } ``` -------------------------------- ### Set Encoder Bandwidth Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Shows how to adjust the MaxBandwidth property of the OpusEncoder to balance between audio fidelity and compression efficiency. ```csharp using OpusDotNet; using (var encoder = new OpusEncoder(Application.VoIP, 48000, 1)) { encoder.MaxBandwidth = Bandwidth.WideBand; encoder.MaxBandwidth = Bandwidth.FullBand; } ``` -------------------------------- ### Forward Error Correction (FEC) Handling Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Explains how to implement Forward Error Correction (FEC) using OpusDotNet to mitigate audio quality degradation caused by packet loss in network transmissions. ```APIDOC ## Forward Error Correction (FEC) Handling ### Description This section details how to handle Forward Error Correction (FEC) with the `OpusDecoder` to recover audio data when packets are lost during transmission. It shows how to simulate packet loss and utilize the decoder's FEC capabilities. ### Method N/A (Class Usage) ### Endpoint N/A (Class Usage) ### Parameters N/A (Class Usage) ### Request Example ```csharp using OpusDotNet; using (var decoder = new OpusDecoder(48000, 2)) { int frameSizeMs = 20; int pcmBufferLength = frameSizeMs * 48000 / 1000 * 2 * 2; byte[] pcmBytes = new byte[pcmBufferLength]; // Simulate receiving packets (some may be lost) byte[][] receivedPackets = /* array of Opus packets, null entries indicate loss */; for (int i = 0; i < receivedPackets.Length; i++) { if (receivedPackets[i] == null) { // Packet lost - attempt FEC recovery // Pass null and -1 to indicate packet loss int recoveredLength = decoder.Decode(null, -1, pcmBytes, pcmBufferLength); Console.WriteLine($"Recovered {recoveredLength} bytes using FEC"); } else { // Normal decode int decodedLength = decoder.Decode(receivedPackets[i], receivedPackets[i].Length, pcmBytes, pcmBufferLength); Console.WriteLine($"Decoded {decodedLength} bytes"); } } } ``` ### Response N/A (Class Usage) ### Response Example N/A (Class Usage) ``` -------------------------------- ### Handle Packet Loss with FEC Source: https://context7.com/mrphil2105/opusdotnet/llms.txt Explains how to utilize Forward Error Correction (FEC) within the OpusDecoder to recover audio data when network packet loss occurs. ```csharp using OpusDotNet; using (var decoder = new OpusDecoder(48000, 2)) { int frameSizeMs = 20; int pcmBufferLength = frameSizeMs * 48000 / 1000 * 2 * 2; byte[] pcmBytes = new byte[pcmBufferLength]; byte[][] receivedPackets = /* array of Opus packets, null entries indicate loss */; for (int i = 0; i < receivedPackets.Length; i++) { if (receivedPackets[i] == null) { int recoveredLength = decoder.Decode(null, -1, pcmBytes, pcmBufferLength); Console.WriteLine($"Recovered {recoveredLength} bytes using FEC"); } else { int decodedLength = decoder.Decode(receivedPackets[i], receivedPackets[i].Length, pcmBytes, pcmBufferLength); Console.WriteLine($"Decoded {decodedLength} bytes"); } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.