NAudio Asio and IeeeFloat format
-
30-05-2021 - |
Question
i have tried to get the sine wave example running on an AsioOut, but it sounds more like a distorted square wave. is it possible that the AsioOut only supports PCM formats? the asio .wav file playback works just fine...
If so, how can i fill my buffers with Ieee floats and convert to PCM? or whats the best way to palyback Ieee on ASIO? i would love to avoid unnecessary sample conversions..
in my code so far, i have tried to generate a sine wave which fits the buffer size, to make sure that i have continuous values, i initialize it with sample rate 44100 and 1 channel. then i pass an instance of the class to the Init() of my AsioOut:
public class SineWaveProvider32 : IWaveProvider
{
private WaveFormat waveFormat;
public WaveFormat WaveFormat
{
get
{
return this.waveFormat;
}
}
public SineWaveProvider32() : this(44100, 1)
{
}
public SineWaveProvider32(int sampleRate, int channels)
{
this.SetWaveFormat(sampleRate, channels);
}
public void SetWaveFormat(int sampleRate, int channels)
{
this.waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channels);
}
public unsafe int Read(byte[] buffer, int offset, int count)
{
var samples = count/4;
fixed(byte* buff = buffer)
{
for (int n = 0; n < samples; n++)
{
var num = (float)(Math.Sin( (2 * Math.PI * n)/ samples ));
((float*)buff)[n] = num;
}
}
return count;
}
}
Solution
Ok i found the bug. Asio is somehow stereo by design. so this code works:
public class SineWaveProvider32 : IWaveProvider
{
private WaveFormat waveFormat;
public WaveFormat WaveFormat
{
get
{
return this.waveFormat;
}
}
public SineWaveProvider32() : this(44100, 2)
{
}
public SineWaveProvider32(int sampleRate, int channels)
{
this.SetWaveFormat(sampleRate, channels);
}
public void SetWaveFormat(int sampleRate, int channels)
{
this.waveFormat = WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channels);
}
public unsafe int Read(byte[] buffer, int offset, int count)
{
var samples = count/4;
fixed(byte* buff = buffer)
{
for (int n = 0; n < samples; n+=2)
{
var num = (float)(Math.Sin( (2 * Math.PI * n * 3)/ samples ));
((float*)buff)[n] = 0;
((float*)buff)[n+1] = num;
}
}
return count;
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow