naudio / NAudio

Audio and MIDI library for .NET
MIT License
5.5k stars 1.1k forks source link

Confusion regarding converting bytes back to floats to process #1121

Open AaronSmithCoding opened 7 months ago

AaronSmithCoding commented 7 months ago

Hey all I am trying to process the buffer from a loopback

I create my capture passing in the samplerate(48000) and Channels(2)

capture = new WasapiLoopbackCapture(device);
 capture.WaveFormat = WaveFormat.CreateIeeeFloatWaveFormat(SampleRate, Channels);
 // Hook up the DataAvailable event to process audio
 capture.DataAvailable += Capture_DataAvailable; 

then during the callback I want to convert the buffer to floats to process and this is my issue...I am new to this stuff so online it shows you have to convert the bytes back to floats

// Convert the bytes to floats for processing var samples = new float[e.BytesRecorded / 3]; for (int i = 0; i < e.BytesRecorded; i += 3) { // Convert the 24-bit sample to float int sample = e.Buffer[i] | (e.Buffer[i + 1] << 8) | (e.Buffer[i + 2] << 16); samples[i / 3] = sample / (float)0x7FFFFF; } // Split the samples into left and right channels float[] leftChannel = new float[samples.Length / 2]; float[] rightChannel = new float[samples.Length / 2]; for (int i = 0; i < samples.Length; i += 2) { leftChannel[i / 2] = samples[i]; rightChannel[i / 2] = samples[i + 1]; }

my question here is when I am only playing audio which is only in left ear I would expect all the left channels to have values and then the right channel to be all 0's?

but currently both arrays are full of non 0 data

What am I missing here or am I completely off tracks?

markheath commented 7 months ago

I've replied on Stack Overflow, but essentially the audio is already floating point, not 24 bit. So I recommend using WaveBuffer as an easy way to access the recorded audio as floating point