Saturday, June 19, 2010

How to play raw PCM audio data in .NET using C#?

There is a Windows API for that. You can use the .NET Wrapper in RageLib. RageLib can be found in http://code.google.com/p/gtaivtools/source/browse/#svn/trunk/RageLib

class Program
{
    static byte[] _queue = new byte[0];
    static void Filler(IntPtr data, int size)
    {
        var length = Math.Min(size, _queue.Length);
        Marshal.Copy(_queue, 0, data, length);
        _queue = _queue.Skip(size).ToArray();
    }
    static void Main(string[] args)
    {
        var encoded = args[0];
        var decoded = Convert.FromBase64String(encoded);
        var samplingFrequency = 8000;
        var bits = 8;
        var channels = 1;
        var bufferSize = 256;
        var waveFormat = new WaveFormat(samplingFrequency, bits, channels);
        using (var waveOutPlayer = new WaveOutPlayer(-1, waveFormat, bufferSize, 1, Filler))
            while (_queue.Length > 0)
            {
            }
    }
}

No comments: