Search code examples
c#winformsnaudio

Need for thread.sleep() when playing a sound array using DirectSoundOut


dso = new DirectSoundOut(Guid.Parse(AudioOutDevice));
var ms = new MemoryStream(soundArray.ToArray()))
{
    IWaveProvider provider = new RawSourceWaveStream(ms, new WaveFormat());
    dso.Init(provider);
    dso.Play();
    Thread.Sleep(3000);
}

I am able to play sound array through desired output device using the above code, and i am unable to hear the sound if there is thread.sleep. But I am unable to understand the reason for using thread.sleep. Can any one let me know the reason for thread.sleep()


Solution

  • The call to Play is not blocking. It simply starts playback. So you must keep dso alive until playback ends or you have stopped it manually.

    You can use code like this if you want to block yourself (obviously only use this if your audio isn't infinitely long)

    dso.Play();
    while (dso.PlaybackState == PlaybackState.Playing)
    {
        Thread.Sleep(500);
    }
    dso.Dispose();