Search code examples
c#.netwavpcmsoundplayer

SoundPlayer not playing any bundled windows sounds PCM wav files


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?


Solution

  • 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.