I am trying to simulate a gameloop in NAudio, I have two loops one for recording and one for playing the audio back. Playback loop works every ~16ms but it sounds weird and choppy.
Here is the code i'm using
static void PlaybackLoop(double dt)
{
int tickSample = 960;
short[] toPlay = new short[tickSample];
if (waitingToPlay.Count > 0)
{
long elapsed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - lastPlayData;
lastPlayData = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
for (int i = 0; i < tickSample; i++)
{
toPlay[i] = waitingToPlay.Count > 0 ? waitingToPlay.Dequeue() : (short)0;
}
// Console.WriteLine(toPlay.Length);
// Console.WriteLine(tickSample * 12);
Console.WriteLine("Volume: " + AvgData(toPlay) + " Length: " + toPlay.Length + " Queue: " + waitingToPlay.Count + " deltatime: " + dt);
byte[] raw = new byte[toPlay.Length * sizeof(short)];
Buffer.BlockCopy(toPlay, 0, raw, 0, toPlay.Length);
bufferedWaveProvider.AddSamples(raw, 0, raw.Length);
_previousTickVoicePlayed = true;
}
}
static void Initialize()
{
NAudio.Wave.WaveInEvent sourceStream = new NAudio.Wave.WaveInEvent();
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(48000, 16, 1);
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable);
sourceStream.StartRecording();
waitingToPlay = new Queue<short>();
NAudio.Wave.WaveOutEvent outputStream = new NAudio.Wave.WaveOutEvent();
bufferedWaveProvider = new BufferedWaveProvider(sourceStream.WaveFormat);
outputStream.Init(bufferedWaveProvider);
outputStream.Play();
}
private static void sourceStream_DataAvailable(object sender, WaveInEventArgs e)
{
short[] sdata = new short[(int)Math.Ceiling(e.BytesRecorded / 2d)];
Buffer.BlockCopy(e.Buffer, 0, sdata, 0, e.BytesRecorded);
int countFirst = waitingToPlay.Count;
foreach (short s in sdata)
{
waitingToPlay.Enqueue(s);
}
int countAfter = waitingToPlay.Count;
Console.WriteLine((DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - LastRecordTime) + " Record ms " + (countAfter - countFirst) + " sample ");
LastRecordTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
static void Main(string[] args)
{
Initialize();
_previousGameTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
while (true)
{
long elapsedTime = (DateTimeOffset.Now.ToUnixTimeMilliseconds() - _previousGameTime);
_previousGameTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
double dt = elapsedTime / 1000f;
// Update the game
PlaybackLoop(dt);
// Update Game at 60fps
Task.Delay(8).Wait();
}
}
I tried to change tickSample
based on dt
but it didn't worked also. I guess i need to do something with waveout but i'm not sure what i need to do, any help is appreciated thanks