Search code examples
c#monogamenaudio

Audio file loaded into memory has 500ms delay before playing


In my game, I'm using the tips and code from this article on fire-and-forget sound with NAudio, using the provided AudioPlaybackEngine, CachedSound, and CachedSoundSampleProvider classes that take an audio file from disc and load its samples into a float[] in memory, playing it by mixing it onto an always-playing MixingSampleProvider.

Right now, this code is being used to play a jump sound when my test player sprite jumps in the air:

private CachedSound jumpSound;
...
jumpSound = new CachedSound(ContentPackageManager.GetAbsoluteFilePath("nsmbwiiJump"));
...
AudioPlaybackEngine.Instance.PlaySound(jumpSound);

However, the sound is played after a 500ms or so delay, regardless of whether I play it from disk or from memory - and the delay is the same. What's going wrong here?


Solution

  • There is some latency due to the buffer durations used by WaveOut under the hood. Basically you are playing one buffer, while filling another. So you are behind the duration of at least one buffer. NAudio lets you configure the buffer durations and number of buffers before initializing your WaveOut device. However, the lower you go, the greater the chance of drop-outs, which will sound like glitches in the audio.