Search code examples
c#.netmultithreadingmediawav

Playing multiple wav files with SoundPlayer() without the sounds overlapping


I am trying to play a .wav file with SoundPlayer(), and then use SpeechSynthesizer() to say a sentence afterwards.

The problem is that SoundPlayer() plays on a new thread, so my program talks while the .wav file is playing. I need it to start speaking after the .wav file has finished.

my example code:

SoundPlayer sound = new SoundPlayer("drum_roll.wav");
sound.Play();

SpeechSynthesizer synth = new SpeechSynthesizer();
synth.Volume = 100;
synth.Speak("Hello World");

Is there a way to stop SoundPlayer() from starting on a new thread, if not how can I achieve the desired result?

P.S. I'm quite new to C# and it is my first time posting a C# related question so any feedback on my code/question (especially the way I tagged this question) is appreciated.


Solution

  • If you can afford stopping your main thread, you can use

    SoundPlayer.PlaySync()
    

    that loads and plays the .wave file on the calling thread.

    .NET SoundPlayer.PlaySync() documentation