using System; using NAudio.Wave.Compression; namespace NAudio.Wave { /// /// MP3 Frame Decompressor using ACM /// public class AcmMp3FrameDecompressor : IMp3FrameDecompressor { private readonly AcmStream conversionStream; private readonly WaveFormat pcmFormat; private bool disposed; /// /// Creates a new ACM frame decompressor /// /// The MP3 source format public AcmMp3FrameDecompressor(WaveFormat sourceFormat) { this.pcmFormat = AcmStream.SuggestPcmFormat(sourceFormat); try { conversionStream = new AcmStream(sourceFormat, pcmFormat); } catch (Exception) { disposed = true; GC.SuppressFinalize(this); throw; } } /// /// Output format (PCM) /// public WaveFormat OutputFormat { get { return pcmFormat; } } /// /// Decompresses a frame /// /// The MP3 frame /// destination buffer /// Offset within destination buffer /// Bytes written into destination buffer public int DecompressFrame(Mp3Frame frame, byte[] dest, int destOffset) { if (frame == null) { throw new ArgumentNullException("frame", "You must provide a non-null Mp3Frame to decompress"); } Array.Copy(frame.RawData, conversionStream.SourceBuffer, frame.FrameLength); int sourceBytesConverted = 0; int converted = conversionStream.Convert(frame.FrameLength, out sourceBytesConverted); if (sourceBytesConverted != frame.FrameLength) { throw new InvalidOperationException(String.Format("Couldn't convert the whole MP3 frame (converted {0}/{1})", sourceBytesConverted, frame.FrameLength)); } Array.Copy(conversionStream.DestBuffer, 0, dest, destOffset, converted); return converted; } /// /// Resets the MP3 Frame Decompressor after a reposition operation /// public void Reset() { conversionStream.Reposition(); } /// /// Disposes of this MP3 frame decompressor /// public void Dispose() { if (!disposed) { disposed = true; if(conversionStream != null) conversionStream.Dispose(); GC.SuppressFinalize(this); } } /// /// Finalizer ensuring that resources get released properly /// ~AcmMp3FrameDecompressor() { System.Diagnostics.Debug.Assert(false, "AcmMp3FrameDecompressor Dispose was not called"); Dispose(); } } }