从WasapiLoopbackCapture捕获音频,并转换为muLaw

时间:2018-01-12 19:47:44

标签: c# naudio pcm wasapi mu-law

我正在使用WasapiLoopbackCapture

捕获音频
- format        = IeeeFloat
- SampleRate    = 48000
- BitsPerSample = 32

我需要将其转换为muLaw(8Khz,8位,单声道) - 最终它将通过SIP中继发送到手机。我已经尝试了100个样本(大部分都是使用NAudio)和解决方案,但仍然不知道如何做到这一点......

1 个答案:

答案 0 :(得分:2)

NAudio中的Mu-Law工具有限,因此您可能需要自己动手。

您需要设置一系列IWaveProvider过滤器以转换为单声道,更改比特率并更改位深度。

waveBuffer = new BufferedWaveProvider(waveIn.WaveFormat);
waveBuffer.DiscardOnBufferOverflow = true;
waveBuffer.ReadFully = false;  // leave a buffer?

sampleStream = new WaveToSampleProvider(waveBuffer);

// Stereo to mono
monoStream = new StereoToMonoSampleProvider(sampleStream)
    {
        LeftVolume = 1f,
        RightVolume = 1f
    };

// Downsample to 8000
resamplingProvider = new WdlResamplingSampleProvider(monoStream, 8000);

// Convert to 16-bit in order to use ACM or MuLaw tools.
ieeeToPcm = new SampleToWaveProvider16(resamplingProvider);

然后为下一步创建自定义IWaveProvider。

// In MuLawConversionProvider
public int Read(byte[] destinationBuffer, int offset, int readingCount)
{
    // Source buffer has twice as many items as the output array.
    var sizeOfPcmBuffer = readingCount * 2;
    _sourceBuffer = BufferHelpers.Ensure(_sourceBuffer, sizeOfPcmBuffer);
    var sourceBytesRead = _sourceProvider.Read(_sourceBuffer, offset * 2, sizeOfPcmBuffer);
    var samplesRead = sourceBytesRead / 2;

    var outIndex = 0;
    for (var n = 0; n < sizeOfPcmBuffer; n += 2)
    {
        destinationBuffer[outIndex++] = MuLawEncoder.LinearToMuLawSample(BitConverter.ToInt16(_sourceBuffer, offset + n));
    }

    return samplesRead * 2;
}

新提供商可以直接发送到WaveOut

outputStream = new MuLawConversionProvider(ieeeToPcm);
waveOut.Init(outputStream);
waveOut.Play();

这些过滤器保留在原位,BufferedWaveProvider为“root”。只要您拨打BufferedWaveProvider.AddSamples(),数据就会通过所有这些过滤器。