简体   繁体   English

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

[英]NAudio converting samples buffer to wave buffer

My goal - to make processing and playback of audio data in real-time by NAudio. 我的目标-由NAudio实时处理和播放音频数据。 The application uses different formats: 8bit pcm, 16bit pcm, 24bit pcm. 该应用程序使用不同的格式:8bit pcm,16bit pcm,24bit pcm。 For playback, I use WaveOut and BufferedWaveProvider. 对于回放,我使用WaveOut和BufferedWaveProvider。 The difficulty arises with the processing of individual samples in real time. 困难在于实时处理单个样本。 To convert raw data into samples, I use the following code: 要将原始数据转换为样本,我使用以下代码:

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

The question is how to convert the samples buffer back to the wave buffer, to play it? 问题是如何将采样缓冲区转换回波形缓冲区以进行播放?

I wrote my own code to solve this problem. 我编写了自己的代码来解决此问题。

    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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM