簡體   English   中英

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

問題是如何將采樣緩沖區轉換回波形緩沖區以進行播放?

我編寫了自己的代碼來解決此問題。

    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