2

In C# I cannot get SoundPlayer class from System.Media to play any wav from my C:\Windows\Media folder using the following code. All I get is no sound:

String filename = "C:\\Windows\\Media\\tada.wav";
SoundPlayer sp = new SoundPlayer(filename);
sp.Load();
sp.Play();

I have checked the wave file "tada.wav" with a program called "Gspot" that tells me the audio codec is "PCM Audio". I do not receive any compiler warnings or errors and there is no exceptions raised when I run the program. I just do not get any sound. My speakers are on, and I can play the file with Windows Media Player.

Adding the wav as a project resource does not make any difference. Could somebody please help me figure out why I cannot get any sound?

John Saunders
  • 160,644
  • 26
  • 247
  • 397

3 Answers3

1

The Play() method plays the sound a separate thread. That is, the console app spins a new thread in which to play the sound. This is great for Windows applications so that the sound playing does not stop the Windows main thread. In a console app, when the parent thread ends the child threads all die as well. -- thus no sound.

There is a PlaySync() method that does NOT spawn a new thread and thus will keep the console app thread alive until it has finished playing your sound.

SchroedingersCat
  • 487
  • 8
  • 21
0

Are you using this as the body of a main() method in a console application? The application is probably ending, thereby shutting down the thread which plays the audio.

I copied and pasted your code into the main of a new "Visual C# Console Application". I added the "using System.Text;" line at the top of the file, compiled, stepped through it, and it worked. When I ran it (without debugging) I got no sound.

If you add the line:

System.Threading.Thread.Sleep(2000);

After the call to Play(), the application will stay around long enough to play the audio.

PaulPerry
  • 906
  • 5
  • 14
  • This was the answer, I added the Sleep call and problem is solved. Thank you so much for solving this problem. –  Aug 06 '12 at 21:49
  • Correct it was the body of main inside a console application. –  Aug 06 '12 at 21:51
  • Great! Also, you'll want to make sure the integer parameter to sleep is the length (in milliseconds) of the audio file. The 2000 is 2 seconds, but you might need to change it for longer audio files. – PaulPerry Aug 06 '12 at 22:00
0

For me (VS 2022, .net 6, C # 10) it worked:

  1. Import the "tada.wav" file into the main directory.

  2. Change in: Properties (tada.wav) - Copy to Output Directory to: Copy always. Later it was enough to:

     SoundPlayer player = new SoundPlayer("tada.wav");
     player.Load ();
     player.Play ();
    
RB1
  • 1