NAudio 将样本缓冲区转换为波形缓冲区

NAudio converting samples buffer to wave buffer

我的目标 - 通过 NAudio 实时处理和播放音频数据。该应用程序使用不同的格式:8bit pcm、16bit pcm、24bit pcm。对于播放,我使用 WaveOut 和 BufferedWaveProvider。实时处理单个样本会带来困难。要将原始数据转换为样本,我使用以下代码:

var vaweProviderIn = new BufferedWaveProvider(format);
vaweProviderIn.AddSamples(waveBuffer, 0, waveBuffer.Length);
var sampleProvider = vaweProviderIn.ToSampleProvider();
sampleProvider.Read(sampleBuffer, 0, sampleBufferSize);
//samples processing

问题是如何将samples buffer转回wave buffer,播放呢?

我写了自己的代码来解决这个问题。

    private enum BPS {PCM_16Bit = 16, PCM_24Bit = 24};

    /// <summary>
    /// Converting the Sample Buffer to the Byte Buffer
    /// </summary>
    /// <param name="samples"></param>
    /// <param name="format"></param>
    /// <returns></returns>
    private byte[] samplesToVawe(float[] samples, WaveFormat format)
    {
        Int32 intSample;
        UInt32 sample4Byte;
        byte[] byteBuffer = new byte[samples.Length * (format.BitsPerSample / 8)];
        uint byteBufIndex = 0;

        for (uint i = 0; i < samples.Length; i++)
        {
            //convert 1 sample into 4 byte integer
            intSample = (Int32)(samples[i] * Int32.MaxValue);
            sample4Byte = (UInt32)intSample;

            switch((BPS)format.BitsPerSample)
            {
                case BPS.PCM_24Bit:
                    byteBuffer[byteBufIndex++] = (byte)(sample4Byte >> 8);
                    byteBuffer[byteBufIndex++] = (byte)(sample4Byte >> 16);
                    byteBuffer[byteBufIndex++] = (byte)(sample4Byte >> 24);
                    break;

                case BPS.PCM_16Bit:
                    byteBuffer[byteBufIndex++] = (byte)(sample4Byte >> 16);
                    byteBuffer[byteBufIndex++] = (byte)(sample4Byte >> 24);
                    break;
            }                
        }

        return byteBuffer;
    }