Raheel Khan Raheel Khan - 29 days ago 7
C# Question

Playing raw PCM with NAudio (outputs noise but opens fine in Audacity)

I am using NAudio (1.7.1.17) WasapiLoopbackCapture which works fine and I can open the saved Raw PCM in Audacity with the following format:

Raw PCM Format

Calling code targeting .NET 4 x86. The file is a 10 second recording totalling [3,515,904 bytes].

CAPTURE:

var device = WasapiLoopbackCapture.GetDefaultLoopbackCaptureDevice();

using (var capture = new WasapiLoopbackCapture(device))
{
capture.ShareMode = AudioClientShareMode.Shared;
capture.DataAvailable += WasapiCapture_DataAvailable;
capture.RecordingStopped += WasapiCapture_RecordingStopped;

// Verified that [capture.WaveFormat] is [44.1KHz, 32 bit 2 ch].

capture.StartRecording();
Thread.Sleep(TimeSpan.FromSeconds(10));
capture.StopRecording();
}

private void WasapiCapture_DataAvailable (object sender, WaveInEventArgs e)
{
// Write [e.BytesRecorded] number of bytes from [e.Buffer] to a file.
}

private void WasapiCapture_RecordingStopped (object sender, StoppedEventArgs e)
{
// Verified that e.Exception was null.
}


PLAYBACK:

var file = new FileInfo(/* Same file that was just recorded. */);

using (var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
var waveOut = new WaveOut();
var waveFormat = new WaveFormat(44100, 32, 2); // Same format.
var rawSource = new RawSourceWaveStream(stream, waveFormat);
waveOut.Init(rawSource);
waveOut.Play();
}


The playback code produces noise that is at most one second long. I double-checked the byte-order and everything looks good except for the size (which should ideally be [3,528,000 bytes]. I'm not sure if padding is the issue here I need to be able to stream this Raw PCM data without knowing the full size in advance.

But first things first. Any pointers on how to get NAudio to play this file would be appreciated.

Answer

Your WaveFormat encoding needs to be IEEE float not PCM (which it currently is)

WaveFormat.CreateIeeeFloatWaveFormat(44100,2)