I'm working on a method where the idea is, first play the sound from start to end, and loop the sound from the sample X to the end and return to that X and play it indefinitely until the user clicks the stop button.
For this I've been using this tutorial: http://mark-dot-net.blogspot.com/2009/10/looped-playback-in-net-with-naudio.html
I've changed a bit the "buttonStartStop_Click" method, my method is:
internal void PlayAudioLoopOffset(WaveOut AudioPlayer, byte[] PCMData, int Frequency, int Pitch, int Bits, int Channels, int Pan, int loopPosition)
{
if (WaveOut.DeviceCount > 0)
{
if (AudioPlayer.PlaybackState == PlaybackState.Stopped)
{
AudioSample = new MemoryStream(PCMData);
using (LoopStream loop = new LoopStream(new RawSourceWaveStream(AudioSample, new WaveFormat(Frequency + Pitch, Bits, Channels))))
{
loop.Position = loopPosition;
VolumeSampleProvider volumeProvider = new VolumeSampleProvider(loop.ToSampleProvider());
PanningSampleProvider panProvider = new PanningSampleProvider(volumeProvider)
{
Pan = (Pan / 100)
};
AudioPlayer.DeviceNumber = GlobalPreferences.DefaultAudioDevice;
AudioPlayer.Volume = 1;
AudioPlayer.Init(panProvider);
AudioPlayer.Play();
}
}
}
else
{
//Show Error
MessageBox.Show(GenericFunctions.resourcesManager.GetString("NoAudioDevices"), "EuroSound", MessageBoxButtons.OK, MessageBoxIcon.Error);
//Stop and dispose
StopAudio(AudioPlayer);
}
}
What's the problem I'm having?
When I click play, the sound starts on the X position instead of starting from the start, and then loops the sound from the start to the end indefinitely instead of from the sample X.
Represented with an image, the idea is to do this:

Thanks to @Hazrelle now I'm a bit closer, but there's another problem, there's a bit of delay when the first audio stops and the second one starts to play, here's a recording: https://drive.google.com/file/d/1nG7OFv2QaA1FIaNM27UKWxrKw6yIco6d/view?usp=sharing
This is the new code I'm using:
internal void PlayAudioLoopPoint(WaveOut AudioPlayer, uint LoopPos, decimal Volume, byte[] PCMData, int Frequency, int Pitch, int Bits, int Channels, decimal AudioPan)
{
MemoryStream AudioSample = new MemoryStream(PCMData);
WaveFormat soundWavFormat = new WaveFormat(CalculateValidRate(Frequency, Pitch), Bits, Channels);
RawSourceWaveStream FullStream = new RawSourceWaveStream(AudioSample, soundWavFormat);
AudioPlayer.Init(FullStream);
AudioPlayer.Play();
AudioPlayer.PlaybackStopped += (se, ev) => audioPlayer_PlaybackStopped(AudioPlayer, PCMData, AudioSample, soundWavFormat, (int)LoopPos);
}
private void audioPlayer_PlaybackStopped(WaveOut AudioPlayer, byte[] PCMData, MemoryStream AudioSample, WaveFormat soundWavFormat, int LoopPos)
{
MemoryStream SubsetStream = new MemoryStream(PCMData, LoopPos, (int)AudioSample.Length - LoopPos);
LoopStream LoopStream = new LoopStream(new RawSourceWaveStream(SubsetStream, soundWavFormat));
AudioPlayer.Init(LoopStream);
AudioPlayer.Play();
}