using System; namespace AX.AudioSystem { public class OpusDecoder : IDisposable { public const int FrameMaxSize = 5760; private IntPtr handle = IntPtr.Zero; private int channels; public OpusDecoder(SamplingRate samplingRate, Channel channels) { if (samplingRate != SamplingRate.Sampling08000 && samplingRate != SamplingRate.Sampling12000 && samplingRate != SamplingRate.Sampling16000 && samplingRate != SamplingRate.Sampling24000 && samplingRate != SamplingRate.Sampling48000) throw new ArgumentOutOfRangeException("samplingRate"); if (channels != Channel.Mono && channels != Channel.Stereo) throw new ArgumentOutOfRangeException("channels"); this.channels = (int)channels; handle = OpusNative.OpusDecoderCreate(samplingRate, channels); } public int Decode(byte[] packetData, float[] pcm) { int bandwidth = OpusNative.opus_packet_get_bandwidth(packetData); int samplesDecoded = 0; if (bandwidth == (int)OpusErrorCode.InvalidPacket) samplesDecoded = OpusNative.OpusDecode(handle, null, pcm, channels, 0); else samplesDecoded = OpusNative.OpusDecode(handle, packetData, pcm, channels, 0); return samplesDecoded; } public int Decode(byte[] packetData, short[] pcm) { int bandwidth = OpusNative.opus_packet_get_bandwidth(packetData); int samplesDecoded = 0; if (bandwidth == (int)OpusErrorCode.InvalidPacket) samplesDecoded = OpusNative.OpusDecode(handle, null, pcm, channels, 0); else samplesDecoded = OpusNative.OpusDecode(handle, packetData, pcm, channels, 0); return samplesDecoded; } public void Dispose() { if (handle != IntPtr.Zero) { OpusNative.OpusDecoderDestroy(handle); handle = IntPtr.Zero; } } } }