感谢 @GoodNightNerdPride在 NAudio GitHub 页面上向我指出这个问题。通过那里发布的代码片段,我能够编写这个方法,它可以将缓冲区从 WasapiLoopbackCapture 对象转换为 16 位 PCM 格式。
/// <summary>
/// Converts an IEEE Floating Point audio buffer into a 16bit PCM compatible buffer.
/// </summary>
/// <param name="inputBuffer">The buffer in IEEE Floating Point format.</param>
/// <param name="length">The number of bytes in the buffer.</param>
/// <param name="format">The WaveFormat of the buffer.</param>
/// <returns>A byte array that represents the given buffer converted into PCM format.</returns>
public byte[] ToPCM16(byte[] inputBuffer, int length, WaveFormat format)
{
if (length == 0)
return new byte[0]; // No bytes recorded, return empty array.
// Create a WaveStream from the input buffer.
using var memStream = new MemoryStream(inputBuffer, 0, length);
using var inputStream = new RawSourceWaveStream(memStream, format);
// Convert the input stream to a WaveProvider in 16bit PCM format with sample rate of 48000 Hz.
var convertedPCM = new SampleToWaveProvider16(
new WdlResamplingSampleProvider(
new WaveToSampleProvider(inputStream),
48000)
);
byte[] convertedBuffer = new byte[length];
using var stream = new MemoryStream();
int read;
// Read the converted WaveProvider into a buffer and turn it into a Stream.
while ((read = convertedPCM.Read(convertedBuffer, 0, length)) > 0)
stream.Write(convertedBuffer, 0, read);
// Return the converted Stream as a byte array.
return stream.ToArray();
}
有了这个,使用 D#+ 将捕获的音频流式传输WasapiLoopbackCapture
到 Discord 就像这样简单:
var stream = connection.GetTransmitSink();
Capture.StartRecording();
Capture.DataAvailable += async (s, a) =>
{
await stream.WriteAsync(ToPCM16(a.Buffer, a.BytesRecorded, Capture.WaveFormat));
};