0

I am trying to play a sound (wav file) in a thread in a test method in Visual Studio. The code below in the test method tries to play the sound file three times. The first play works fine and demonstrates the code that is in the PlaySound method. The second play of the sound also works fine and demonstrates that the PlaySound(path) method works okay.

But the third attempt to play the sound by calling the helper method in a Task fails to play any sound. The code appears to work fine and call the player, etc. But there is no sound. I am wondering if the task thread has access to the speakers or something.

Is it possible to play a sound on a thread in the VS debugger? Thank you.

// play the sound the first time and it works fine async with Play()
// this is the same code as in the PlaySound(path) helper method.
using (var simpleSound = new SoundPlayer(path)) {
  try {
    simpleSound.Load();
    simpleSound.Play(); // async play is okay, PlaySync works too
  }
  catch (Exception ex) {
    Console.WriteLine(ex.Message);
  }
}

// wait 4 seconds and play it again - works fine
Thread.Sleep(4000);
PlaySound(path);

// call it in a task in Visual Studio and there is no sound heard.
// Neither Play() nor PlaySync() works in the thread.
// Do threads in the VS debugger have access to the speaker?
// What can I do to make this example work?
var t1 = new Task(() => PlaySound(path));
t1.Start();
Task.WaitAll();
Kevin
  • 1,548
  • 2
  • 19
  • 34

0 Answers0